Get values as array of elements after $lookup

后端 未结 2 1854
既然无缘
既然无缘 2021-01-22 13:55

For MongoDB, when using $lookup to query more than one collection, is it possible to get a values-only list for a field returned in the $lookup?

<
2条回答
  •  自闭症患者
    2021-01-22 14:17

    Hope below query helps :

    db.foo.aggregate([{
      $lookup: {
        from:"bar",
        localField:"name",
        foreignField: "foo",
        as:"bars"
      }
     },
     {$unwind : '$bars'},
     {
       $group : {
        _id : {
            _id : '$_id',
            name : '$name',
            desc : '$desc'
        },
        bars : { $push : '$bars.name'}
       }
     },
     {
       $project : {
         _id : '$_id._id',
         name : '$_id.name',
         desc : '$_id.desc',
         bars : '$bars'
      }
     }
    ]).pretty()
    

    output :

    {
     "_id" : ObjectId("5ce72e4a5267960532b8df0a"),
     "name" : "foo2",
     "desc" : "second foo",
     "bars" : [
        "bar3"
     ]
    }
    {
     "_id" : ObjectId("5ce72e415267960532b8df09"),
     "name" : "foo1",
     "desc" : "first foo",
     "bars" : [
        "bar1",
        "bar2"
     ]
    }
    

提交回复
热议问题