场景:考虑集合中MongoDB中存在的名为“MyCollection”的文档
{
"_id" : ObjectId("512bc95fe835e68f199c8686"),
"author": "dave",
"score" : 80,
"USER" : {
"UserID": "Test1",
"UserName": "ABCD"
}
},
{ "_id" : ObjectId("512bc962e835e68f199c8687"),
"author" : "dave",
"score" : 85,
"USER" : {
"UserID": "Test2",
"UserName": "XYZ"
}
},
...
我知道UserID
,并想以此为基础进行抓取。
问题:我使用Node.js +MongoDB-本机驱动程序尝试了以下代码:
db.Collection('MyCollection', function (err, collection) {
if (err) return console.error(err);
collection.aggregate([
{ $match: { '$USER.UserID': 'Test2'} },
{$group: {
_id: '$_id'
}
},
{
$project: {
_id: 1
}
}
], function (err, doc) {
if (err) return console.error(err);
console.dir(doc);
});
});
但它并不像预期的那样起作用。
问题:有人知道如何在MongoDB查询中使用$match
操作符吗?
更新:我没有收到任何错误。但是对象将是空的,即[]
发布于 2013-04-16 04:38:12
我尝试了shell,而您的$match
语句在shell中尝试是错误的。
> db.MyCollection.find()
{ "_id" : ObjectId("512bc95fe835e68f199c8686"), "author" : "dave", "score" : 80, "USER" : { "UserID" : "Test1", "UserName" : "ABCD" } }
{ "_id" : ObjectId("512bc962e835e68f199c8687"), "author" : "dave", "score" : 85, "USER" : { "UserID" : "Test2", "UserName" : "XYZ" } }
> db.MyCollection.aggregate([{$match: {"$USER.UserID": "Test2"}}])
{ "result" : [ ], "ok" : 1 }
> db.MyCollection.aggregate([{$match: {"USER.UserID": "Test2"}}])
{
"result" : [
{
"_id" : ObjectId("512bc962e835e68f199c8687"),
"author" : "dave",
"score" : 85,
"USER" : {
"UserID" : "Test2",
"UserName" : "XYZ"
}
}
],
"ok" : 1
}
因此,完整的聚合将是:
db.MyCollection.aggregate([
{$match: {"USER.UserID": "Test2"}},
{$group: {"_id": "$_id"}},
{$project: {"_id": 1}}
])
(您不需要额外的$project
,因为您只在$group
中项目_id
,但是由于_id
是唯一的,您应该只使用$project
并删除$group
)
https://stackoverflow.com/questions/16035309
复制相似问题