在 $lookup 后以元素数组的形式获取值 [英] Get values as array of elements after $lookup

查看:15
本文介绍了在 $lookup 后以元素数组的形式获取值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

解决方案

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

这篇关于在 $lookup 后以元素数组的形式获取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆