在以下记录中我想得到item_details类型为“system”且id为“7634e9639f5c25f2434b72d8a” var operator = { 'item_details': { $elemMatch: { type: 'custom' } } } var query = { _id : "7634e9639f5c25f2434b72d8a" }; req.db.collectio
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); });
它只返回第一个元素.但需要获取与查询和投影匹配的所有记录.下面是我想要查询的示例数据.
[ { "_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); });