MongoDB 求教 mongoid 的 embed_many 查询写法

hhuai · March 11, 2013 · Last by ashchan replied at March 11, 2013 · 3155 hits

在 mongodb 的命令行中可以这么查 db.ents.find({"categories._id": ObjectId("513d31ae69aa46135d000002")})

在 mongoid 上要怎么查呢,怎么写也不对,文档都翻烂了。

2.0.0-p0 :049 > Ent.where({"categories._id" => "513d31ae69aa46135d000002"})
 => #<Mongoid::Criteria
  selector: {"categories._id"=>"513d31ae69aa46135d000002"}
  options:  {}
  class:    Ent
  embedded: false>

这样写是错误的,无法表现出 ObjectId

@hhuai

embeds_many

Model#{name}.find Return documents in the relation with matching ids. Will raise an error if all the ids are not found > > by default.

其实,许多东西官网都有有说明的。书出版之后,都会成为旧的了。

#1 楼 @shatle 嗯,我主要是看官网的文档,你说的这个我已经看过了。 不过你说的这个种方法不能满足我的要求。 我需要的是 Model 的类方法,不是实例方法,就是说我的查询条件只有 category,没有 ent 的,我不管是哪一个 ent.

仔细看一下我的这个原生查询方法 db.ents.find({"categories._id": ObjectId("513d31ae69aa46135d000002")})

你的 model 是 category embeds_many ents 吗?如果是的话 ents 是内嵌在 category 下的,思路是拿到 category 再拿 ents:

Category.where(_id: "513d31ae69aa46135d000002").ents

#3 楼 @ashchan 反了,我的 category 在 ent 下面,我给出图吧。

class Ent
    include Mongoid::Document
    field :name, type: String
    embeds_many :categories
end

class Category
    include Mongoid::Document
    field :name,            type: String
    embedded_in :ent, inverse_of: :categories
end

查询条件是 Category 的 id, 目的就是找出哪一个 Category, Category 是 embed_in 的,我试了 Category.find 这样是找不着的。

@hhuai

突然想问你,你想找出的是什么?是 ents? 还是 categories?

如果是 ents, 试试

Ent.all.elem_match(categories: {id: "124123123213"})

如果是 categories, 我觉得你应该设计为 :has_many

#4 楼 @hhuai 这样的话你自己写的应该是对的:

Ent.where({ "categories._id" => ObjectId("513d31ae69aa46135d000002") })
You need to Sign in before reply, if you don't have an account, please Sign up first.