如何在MongoDB中查询引用

时间:2014-07-02 00:12:48

标签: mongodb

我在网上找到了这个教程很有帮助。但是它显示了一个使用两个objectIds数组的示例。如果它是一个objectId而不是两个,那么如何进行查询呢?

http://www.tutorialspoint.com/mongodb/mongodb_relationships.htm

{
   "_id":ObjectId("52ffc33cd85242f436000001"),
   "contact": "987654321",
   "dob": "01-01-1991",
   "name": "Tom Benzamin",
   "address_ids": [
      ObjectId("52ffc4a5d85242602e000000"), // if this was not an array and just one ObjectId
      ObjectId("52ffc4a5d85242602e000001") 
   ]
}

var result = db.users.findOne({"name":"Tom Benzamin"},{"address_ids":1})
var addresses = db.address.find({"_id":{"$in":result["address_ids"]}}) 

1 个答案:

答案 0 :(得分:0)

我希望我做对了。所以你有这种元素:

{
   "_id":ObjectId("52ffc33cd85242f436000001"),
   ...
   "address_ids": ObjectId("52ffc4a5d85242602e000000")
}

您的代码如下所示:

var result = db.users.findOne({"name":"Tom Benzamin"},{"address_ids":1})
var addresses = db.address.find({"_id": result["address_ids"]})