Mongodb使用filter在子文档中获取logging

在以下logging中,我想获得item_details,其中type是“ system ”,id是“ 7634e9639f5c25f2434b72d8a

var operator = { 'item_details': { $elemMatch: { type: 'custom' } } } var query = { _id : "7634e9639f5c25f2434b72d8a" }; req.db.collection('products').find(query, operator).toArray(function (err, result) { if(err)throw err; console.log(result); }); 

它只返回第一个元素。 但是需要获取与查询和投影相匹配的所有logging。 以下是我想查询的示例数据。

  [ { "_id": "7634e9639f5c25f2434b72d8a", "item_details": [ { "quantity": 1, "sub_total": 1201, "type": "system" }, { "quantity": 19, "sub_total": 140, "type": "custom" }, { "quantity": 81, "sub_total": 130, "type": "custom" }, { "quantity": 71, "sub_total": 90, "type": "system" } ] }, { "_id": "564e9639f5c25f2434b72d8a", "item_details": [ { "quantity": 1, "sub_total": 101, "type": "system" }, { "quantity": 9, "sub_total": 40, "type": "custom" }, { "quantity": 8, "sub_total": 30, "type": "custom" }, { "quantity": 7, "sub_total": 60, "type": "system" } ] } ] 

$ elemmatch只会给你数组的第一个元素(在子文档中)。 见下文http://docs.mongodb.org/manual/reference/operator/projection/elemMatch/

所以我们宁可用点符号来得到你想要的。

 req.db.collection('products').find({"_id": "7634e9639f5c25f2434b72d8a", "item_details.type": "custom"}).toArray(function(err, result) { if (err) throw err; console.log(result); });