Mongo查找加入objectid无法正常工作?

use*_*858 4 mongodb mongodb-query

对于集合:

 data:
 { "_id" : ObjectId("57a"), "rep" : ObjectId("570"), "label" : "pat" }
 { "_id" : ObjectId("57b"), "rep" : ObjectId("571"), "label" : "pat" }

 rep:
 { "_id" : ObjectId("570") }
 { "_id" : ObjectId("571") }
Run Code Online (Sandbox Code Playgroud)

db.rep.aggregate([{$ lookup:{from:"data",localField:"rep",foreignField:"_ id",as:"in_common"}}])

产生一个空集.

查询应该生成两行结果.

我怎样才能解决这个问题?

Cle*_*ath 10

您需要修改您的查询,如下所示

db.data.aggregate([ { $lookup: {from: "rep", localField:"rep", foreignField:"_ id", as: "in_common" }}])

此查询将为您提供两条记录.

没有获取记录的原因:在您的集合中,您没有data._id到rep._id的映射,而您有从rep._id到data.rep的映射

https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/

{
   $lookup:
     {
       from: <collection to join>,
       localField: <field from the input documents>,
       foreignField: <field from the documents of the "from" collection>,
       as: <output array field>
     }
}
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你!

  • 谢谢,那行得通。当插入实际的ObjectId值时,查询似乎返回太多值。使用的查询是:db.data.aggregate([{$ lookup:{from:“ rep”,localField:“ ObjectId(_id)”,foreignField:“ ObjectId(rep)”,as:“ incommon”}}]])针对“ ObjectId(rep)”搜索“ ObjectId(_id)”的格式是否正确? (2认同)