在以下记录中我想得到item_details类型为“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); });
它只返回第一个元素.但需要获取与查询和投影匹配的所有记录.下面是我想要查询的示例数据.
[ { "_id": "7634e9639f5c25f2434b72d8a","item_details": [ { "quantity": 1,"sub_total": 1201,"type": "system" },{ "quantity": 19,"sub_total": 140,"type": "custom" },{ "quantity": 81,"sub_total": 130,{ "quantity": 71,"sub_total": 90,"type": "system" } ] },{ "_id": "564e9639f5c25f2434b72d8a","sub_total": 101,{ "quantity": 9,"sub_total": 40,{ "quantity": 8,"sub_total": 30,{ "quantity": 7,"sub_total": 60,"type": "system" } ] } ]
解决方法
$elemmatch只会给你数组的第一个元素(在子文档中).
见下文
http://docs.mongodb.org/manual/reference/operator/projection/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); });
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。