在mongodb的参考数组中查找

时间:2014-01-16 22:09:39

标签: javascript mongodb mongoose

我有这种模式:

MyCollection
{
  ...
  groups : [{ type: Schema.Types.ObjectId, ref: 'Group' }],
  ...
}

现在如何查找具有已知_id组的所有文档? 我试过了

MyCollection.find({
                'groups' : {
                  $elemMatch : {
                    '$ref' : 'Group',
                    '$id'  : myid
                  }
                }
             }).exec(cb);

但它不起作用。我真的很沮丧这个问题。

示例文件:

{ _id: 52d7dd87f3f1e72c7c000005,
   groups: [ { _id: 52d02565360c206933000013, name: 'groupname' } ],
   date: Thu Jan 16 2014 10:15:00 GMT+0200 (EET),
   ...
}

另一次尝试:

> db.groups.find({ "name" : "NINFOS13"})
{ "_id" : ObjectId("52d8fad69c7817b52a000012"), "createdAt" : ISODate("2014-01-  17T09:41:42.365Z"), "name" : "NINFOS13", "__v" : 0 }
> db.subjects.insert({groups : [ { _id : ObjectId("52d8fad69c7817b52a000012"), name : "NINFOS13"}]})
> db.subjects.find()
{ "_id" : ObjectId("52d8fb7c1c4493a980630c68"), "groups" : [  {  "_id" : ObjectId("52d8fad69c7817b52a000012"),  "name" : "NINFOS13" } ] }
> db.subjects.find({"groups._id" : ObjectId("52d8fb7c1c4493a980630c68")}).count()
0

抱歉,这个查询有误!

1 个答案:

答案 0 :(得分:1)

适合我(使用mongo shell):

> db.stack.insert({groups: [ { _id: ObjectId("52d02565360c206933000013"), name: "groupname" } ]});    

> db.stack.find()
{ "_id" : ObjectId("52d8924b5c90ea648f2a4664"), "groups" : [  {  "_id" : ObjectId("52d02565360c206933000013"),  "name" : "groupname" } ] }

> db.stack.find({"groups._id": ObjectId("52d02565360c206933000013")});
{ "_id" : ObjectId("52d8924b5c90ea648f2a4664"), "groups" : [  {  "_id" : ObjectId("52d02565360c206933000013"),  "name" : "groupname" } ] }

也许你有一个错字。