【问题标题】:How to retrieve only few fields from another collection如何从另一个集合中仅检索几个字段
【发布时间】:2019-01-31 19:40:13
【问题描述】:

我有两个收藏

Collection_foo :

{
    cid:'1234',
    'foo':'bar',
    some 10+ fields...
}

收藏栏:

{
    cid:'1234',
    'foobar':'barfoo',
    some 10+ fields...
}

我想加入这个收藏

我尝试使用 $lookup、$unwind、$project

aggregate([
    {
        $lookup:{
            from: 'Collection_bar',
            localField: 'cid',
            foreignField: 'cid',
            as: 'collection_foo_bar',
        }
    },
    { $unwind :'collection_foo_bar' },
    { 
        $project : {
             'foobar':'collection_foo_bar.foobar', 
             collection_foo_bar : 0 //
        }
    }
])

我也试过了,但是出错了

{ 
    $project : {
        'foobar':'collection_foo_bar.foobar', 
        collection_foo_bar : 0 
    }
}

现在我明白了

{
    'foobar':'barfoo'

}

我想要这个

{
    cid:'1234',
    'foo':'bar',
    some 10+ fields...,
    'foobar':'barfoo'
}

第二个集合中只有 1 个字段。

【问题讨论】:

标签: javascript node.js mongodb aggregate


【解决方案1】:

请看一下这个。 变体 1。

db.Collection_foo.aggregate([
    {
    $lookup:{
        from: "Collection_bar",
        localField: "cid",
        foreignField:"cid",
        as: "collection_foo_bar"
    },  
    },
    { $unwind :'$collection_foo_bar' },      
   {
      $replaceRoot: { 
          newRoot: { 
              $mergeObjects: [ "$$ROOT",{foobar:"$collection_foo_bar.foobar"}] 
          } 
      }
   },   
   { $project: { collection_foo_bar: 0 } }

])

变体 2

db.Collection_foo.aggregate([
    {
    $lookup:{
        from: "Collection_bar",
        localField: "cid",
        foreignField:"cid",
        as: "collection_foo_bar"
    },  
    },
    { $unwind :'$collection_foo_bar' },      
   {
      $addFields: {foobar:"$collection_foo_bar.foobar"}
   },   
   { $project: { collection_foo_bar: 0 } }
])

结果

{
    "_id" : ObjectId("5c51a1479b70d343fb47d3ae"),
    "cid" : "1234",
    "foo" : "bar",
    "f1" : 1.0,
    "f23" : 2,
    "f33" : 3,
    "foobar" : "barfoo1111"
}

第二个集合中的“foobar”和第一个集合中的其他字段。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-05
    • 2023-03-05
    • 2016-08-30
    • 1970-01-01
    • 2017-07-12
    • 2021-09-07
    • 2019-01-28
    • 2011-05-17
    相关资源
    最近更新 更多