首页 文章

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

提问于
浏览
1

对于集合:

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

 rep:
 { "_id" : ObjectId("570") }
 { "_id" : ObjectId("571") }

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

产生一个空集 .

查询应该生成两行结果 .

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

1 回答

  • 6

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

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

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

    Reason for not getting the records :在您的集合中,您没有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>
         }
    }
    

    希望能帮助到你!

相关问题