node.js - mongodb shell 和 node.js 中的相同查询表现不同

标签 node.js mongodb mongodb-query

为什么会发生这种情况?对于这种差异有合乎逻辑的解释吗?

例如,我有一个数据库结构;

{
    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管道作为数组,而不是作为单独的参数。

所以应该是:

db.collection.aggregate([{$unwind: "$category.groups"},
                         {$match: {"category.groups.groupName": "groupName2",
                                  "category.name": "name1"}}
                        ]).toArray(function(err, result) { ... });

shell version更宽容,但为了安全起见,您应该始终使用数组,否则不能包含 options 参数。

关于node.js - mongodb shell 和 node.js 中的相同查询表现不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36357716/

相关文章:

jquery - "Typeahead is not a function"错误

javascript - 如何删除 map() 中的重复项

node.js - NodeJS : if I return mysql data to client in the end of request does it mean that having callbacks doesn't make sense?

MongoDB 没有记录到日志文件

Node.Js MongoDB 在获取列表时格式化日期

javascript - 通过 node.js 将字符串传递给 shell 脚本的标准输入

mongodb - 我的 mongoexport 的 json 格式不断出现错误

mongodb - MongoDB身份验证无法在Grails中运行,但可以通过控制台进行

mongodb - 如何按月对文件进行分组?

javascript - Meteor:使用reactiveVar观察集合