MongoDB返回对象的嵌套数组减去对象内的属性(.then()也不适用于聚合)

问题描述 投票:1回答:2

我对mongodb还是很陌生,很难为我的用例找到解决方案。例如,我有以下文档:

{ 
   _id : ObjectId('5rtgwr6gsrtbsr6hsfbsr6bdrfyb'),
   uuid : 'something',
   mainArray : [
       {
           id : 1,
           title: 'A',
           array: ['lots','off','stuff']
       },
       {
           id : 2,
           title: 'B',
           array: ['even','more','stuff']
       }
   ]
}

我想返回以下内容:

{ 
   uuid : 'something',
   mainArray : [
       {
           id : 1,
           title: 'A'
       },
       {
           id : 2,
           title: 'B'
       }
   ]
}

我已经尝试过将findOne()aggregate()$slice$project结合使用的各种组合。使用findOne(),如果它完全起作用,将返回who文档。我无法测试是否尝试进行汇总工作,因为.then((ret)=>{})承诺对我来说似乎在node.js中不起作用(findOne没有问题)。像这样调用一个函数

return db.myCollection.aggregate([
    {
       $match: {
          _id:ObjectId(mongo_id)
       }  
    },
    {
        $project : {
            mainArray: {
                id:1,
                title:1
            }
        }
    }
],function(err,res){
    console.log(res)
    return res
})

记录整个功能,而不记录我要查找的机器人。

node.js arrays mongodb nested slice
2个回答
1
投票

您缺少toArray()方法来获取实际结果集。相反,您将返回聚合游标对象。试试这个。

return db.myCollection.aggregate([matchCode,projectCode]).toArray().then(
     data => { 
              console.log(data); 
              return data; 
             }, 
     error => { console.log(error)});

MongoDB NodeJS驱动程序在聚集光标上的文档可以 在这里找到 http://mongodb.github.io/node-mongodb-native/3.5/api/AggregationCursor.html#toArray


1
投票

这是替代解决方案(对于@ v1shva在comment中提到的解决方案)

代替使用聚合,可以使用projection操作的.findOne()选项。

db.myCollection.findOne(matchCode, { 
  projection: { _id: false, 'mainArray.array': false } // or { _id: -1, 'mainArray.array': -1 }
})
© www.soinside.com 2019 - 2024. All rights reserved.