[英]Need to fetch one documents per user nodejs and mongodb
我有下面提到的结构文件: -
{
"_id" : ObjectId("585d64f356ec921620c5d7c5"),
"createdAt" : ISODate("2016-12-23T17:54:59.193Z"),
"updatedAt" : ISODate("2016-12-23T17:54:59.193Z"),
"userid" : ObjectId("5850f42b9a8ea0a43c1355b8"),
"destination" : {
"id" : ObjectId("584fdcf0e6be59514784e9d4"),
"lineid" : ObjectId("584f8ddd433c5703acf2618f")
},
"source" : {
"id" : ObjectId("584fdda2e6be59514784e9df"),
"lineid" : ObjectId("584fdd2fe6be59514784e9d8")
},
"__v" : 0
}
它们是相同结构的多个文档,但重复“userid”字段。 现在我想获取符合条件但每个用户只有一个文档的文档。 我尝试使用“查找”查询,“聚合”和“组”但没有成功。
我能够使用此查询获取记录,但结果数组具有相同用户的多个文档。
Route.find({
$and : [ {
$or : [ {
'source.lineid' : request.payload.sourcelineid
}, {
'destination.lineid' : request.payload.destinationlineid
}, {
'source.id' : request.payload.source
}, {
'destination.id' : request.payload.destination
} ]
}, {
userid : {
$ne : request.user._id
}
} ]
}).sort({
createdAt : -1
})
.exec(function(err, sameroutes) {
if (err) {
reply(err).code(500);
} else {
reply(sameroutes).code(200);
}
});
使用aggregate()
方法,您可以按用户对文档进行分组,并使用$first
或$last
accumulator运算符返回字段。
可以使用$match
使用标准MongoDB查询作为初始管道阶段进行过滤。 运行以下管道应该可以获得所需的结果:
Route.aggregate([
{
"$match": {
"userid": { "$ne": request.user._id },
"$or": [
{ "source.lineid": request.payload.sourcelineid },
{ "destination.lineid" : request.payload.destinationlineid },
{ "source.id" : request.payload.source },
{ "destination.id" : request.payload.destination }
]
}
},
{ "$sort": { "userid": 1, "createdAt": -1 } },
{
"$group": {
"_id": "$userid",
"doc_id": { "$first": "$_id" },
"createdAt": { "$first": "$createdAt" },
"updatedAt": { "$first": "$updatedAt" },
"destination": { "$first": "$destination" },
"source": { "$first": "$source" }
}
}
]).exec(function(err, sameroutes) {
if (err) {
reply(err).code(500);
} else {
reply(sameroutes).code(200);
}
});
我试图运行的聚合查询是99%正确,但我错过的是将所有来自有效负载的ID值转换为ObjectID。 所以正确答案是: -
Route.aggregate([
{
"$match": {
"userid": { "$ne": request.user._id },
"$or": [
{ "source.lineid": mongo.ObjectId(request.payload.sourcelineid) },
{ "destination.lineid" : mongo.ObjectId(request.payload.destinationlineid) },
{ "source.id" : mongo.ObjectId(request.payload.source) },
{ "destination.id" : mongo.ObjectId(request.payload.destination) }
]
}
},
{ "$sort": { "userid": 1, "createdAt": -1 } },
{
"$group": {
"_id": "$userid",
"doc_id": { "$first": "$_id" },
"createdAt": { "$first": "$createdAt" },
"updatedAt": { "$first": "$updatedAt" },
"destination": { "$first": "$destination" },
"source": { "$first": "$source" }
}
}
]).exec(function(err, sameroutes) {
if (err) {
reply(err).code(500);
} else {
reply(sameroutes).code(200);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.