为什么会这样?这种差异有合理的解释吗?
例如,我的数据库结构为;
{
id: "1"
category: {
name: "name1"
groups: [
{
groupName : "groupName1"
title: ""
},
{
groupName : "groupName2"
title: ""
}
]
}
}
查询如下;
db.collection.aggregate({$unwind:"$category.groups"},
{$match:{"category.groups.groupName": "groupName2",
"category.name" : "name1"}})
在mongo shell中,它返回为;
{
id: "1"
category: {
name: "name1"
groups: [
groupName : "groupName2"
title: ""
]
}
}
在node.js中查询;
db.collection.aggregate({$unwind:"$category.groups"},
{$match:{"category.groups.groupName": "groupName2",
"category.name" : "name1"}}).
toArray(function(err, result) {
if (result) {
debugger;
var res = result;
}
});
};
node.js中的结果就像;
{
id: "1"
category: {
name: "name1"
groups: [
{
groupName : "groupName1"
title: ""
},
{
groupName : "groupName2"
title: ""
}
]
}
}
答案 0 :(得分:2)
使用node.js驱动程序,您需要将aggregate
管道作为数组传递,而不是作为单独的参数传递。
所以它应该是:
db.collection.aggregate([{$unwind: "$category.groups"},
{$match: {"category.groups.groupName": "groupName2",
"category.name": "name1"}}
]).toArray(function(err, result) { ... });
shell version更宽容,但为了安全起见,您应该始终使用数组,否则请不要包含options
参数。