在$ lookup之后获取值作为元素数组

时间:2019-05-24 00:06:31

标签: mongodb mongodb-query aggregation-framework

对于MongoDB,当使用$lookup查询多个集合时,是否可以获得$lookup中返回的字段的仅值列表?

我不需要的是完整对象及其所有键/值的列表。

数据

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"
}

所需的查询输出

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

最近

该查询似乎已经存在,但是它在bars字段中返回了太多数据:

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

2 个答案:

答案 0 :(得分:4)

只需在.dot字段中使用name表示法

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

MongoPlayground

答案 1 :(得分:2)

希望以下查询有帮助:

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()

输出:

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