在mongodb shell和node.js中的相同查询的行为是不同的
为什么发生这种情况? 这种差异是否有合理的解释?
例如,我有一个数据库结构为;
{ 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: "" } ] } }
使用node.js驱动程序,您需要将aggregate
pipe道作为数组传递,而不是单独的参数。
所以它应该是:
db.collection.aggregate([{$unwind: "$category.groups"}, {$match: {"category.groups.groupName": "groupName2", "category.name": "name1"}} ]).toArray(function(err, result) { ... });
shell版本更加宽容,但是为了安全起见,您应该始终使用数组,否则就不能包含options
参数。