2016-04-01 25 views
2

爲什麼會發生這種情況?這種差異是否有合理的解釋?在mongodb shell和node.js中查詢的行爲不同

例如我有一個db結構爲;

{ 
    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: "" 
      ] 
     } 
    } 

Query in 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: "" 
     } 
     ] 
    } 
} 
+1

你可以提供一個示例查詢,這是表現這種方式.. –

+0

有什麼區別,你應該更明確 –

+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參數,否則。