Get values as array of elements after $lookup

2020-04-17 05:51发布

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?

What I don't want is a list of the full object with all its key/values.

Data:

failover_tool:PRIMARY> db.foo.find().pretty()
{
    "_id" : ObjectId("5ce72e415267960532b8df09"),
    "name" : "foo1",
    "desc" : "first foo"
}
{
    "_id" : ObjectId("5ce72e4a5267960532b8df0a"),
    "name" : "foo2",
    "desc" : "second foo"
}
failover_tool:PRIMARY> db.bar.find().pretty()
{
    "_id" : ObjectId("5ce72e0c5267960532b8df06"),
    "name" : "bar1",
    "foo" : "foo1"
}
{
    "_id" : ObjectId("5ce72e165267960532b8df07"),
    "name" : "bar2",
    "foo" : "foo1"
}
{
    "_id" : ObjectId("5ce72e1d5267960532b8df08"),
    "name" : "bar3",
    "foo" : "foo2"
}

Desired Query Output

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

Closest

This query seems like it's almost there, but it returns too much data in the bars field:

db.foo.aggregate({
    $lookup: {
        from:"bar",
        localField:"name",
        foreignField: "foo",
        as:"bars"
    }
}).pretty()

2条回答
【Aperson】
2楼-- · 2020-04-17 06:06

Just use .dot notation with the name field

db.foo.aggregate([
  { "$lookup": {
    "from": "bar",
    "localField": "name",
    "foreignField": "foo",
    "as": "bars"
  }},
  { "$addFields": { "bars": "$bars.name" }}
])

MongoPlayground

查看更多
叼着烟拽天下
3楼-- · 2020-04-17 06:14

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"
 ]
}
查看更多
登录 后发表回答