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



我对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)=>{})因为承诺似乎在节点中不起作用.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
})

记录整个函数,而不是我正在寻找的机器人。

缺少获取实际结果集的 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

这是一个替代解决方案(@v1shva评论中提到的解决方案(

您可以使用.findOne()操作选项projection而不是使用聚合。

db.myCollection.findOne(matchCode, { 
projection: { _id: false, 'mainArray.array': false } // or { _id: -1, 'mainArray.array': -1 }
})

相关内容

最新更新