[英]Mongoose Aggregation match an array of objectIds
我有一个看起来像这样的架构
var Post = new mongoose.Schema({
author: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
created: {
type: Date,
Default: Date.now
})
我也有一个用户表。 我有一个用户ID数组,我试图根据一个用户ID数组搜索帖子表
例如
var userIds = ["575e96652473d2ab0ac51c1e","575e96652473d2ab0ac51c1d"] .... and so on
我想返回这些用户创建的所有帖子。 帖子应按其创建日期排序。 有没有一种方法可以根据提供的用户ID对该帖子进行分组,基本上与单个用户的帖子匹配?
我想要达到的结果是这样的:
[{
userAId : "56656.....",
post : [postA, postB],
},{
userBId :"12345...",
post : [postA, postB]
}]
如何编写此查询?
这就是我到目前为止
Post.aggregate([{
// {"$unwind" : ""},
// "$group": {
// _id: "$author",
// "created" : {"$sum" : 1 }
// }
"$match" : { author : id}
}]).exec(function(error, data) {
if(error){
return console.log(error);
}else{
return console.log(data)
}
})
{
"_id" : ObjectId("575e95bc2473d2ab0ac51c1b"),
"lastMod" : ISODate("2016-06-13T11:15:08.950Z"),
"author" : ObjectId("575dac62ec13010678fe41cd"),
"created" : ISODate("2016-06-13T11:15:08.947Z"),
"type" : "photo",
"end" : null,
"commentCount" : 0,
"viewCount" : 0,
"likes" : 0,
"tags" : [],
"title" : "Today is a good day",
"__v" : 0
}
要返回由ID列表中描述的用户创建的所有帖子,请在查询中使用$in
运算符,然后将sort()
方法链接到查询以按创建的日期字段对结果进行排序:
Post.find({ "author": { "$in": userIds } })
.sort("-created") // or .sort({ field: 'asc', created: -1 });
.exec(function (err, data){
if(err){
return console.log(err);
} else {
return console.log(data);
}
});
要获得将每个用户的帖子ID分组的结果,您需要运行以下汇总操作:
Post.aggregate([
{ "$match" : { "author": { "$in": userIds } } },
{ "$sort": { "created": -1 } },
{
"$group" : {
"_id" : "$author",
"posts" : { "$push": "$_id" }
}
},
{
"$project": {
"_id": 0,
"userId": "$_id",
"posts": 1
}
}
]).exec(function (err, result){
if(err){
return console.log(err);
} else {
return console.log(result);
}
});
或使用流畅的API:
Post.aggregate()
.match({ "author": { "$in": userIds } })
.sort("-created")
.group({
"_id" : "$author",
"posts" : { "$push": "$_id" }
})
.project({
"_id" : 0,
"userId" : "$_id",
"posts": 1
})
.exec(function (err, result){
if(err){
return console.log(err);
} else {
return console.log(result);
}
});
没有聚合,这应该是可能的。
Post
.find({ author: { $in: userIds } })
.sort({ created: -1 })
如果出现CastError:转换为ObjectId失败,请确保将userIds数组从字符串数组映射到猫鼬ID数组。
userIds = userIds.map(userId => new mongoose.Types.ObjectId(userId))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.