簡體   English   中英

貓鼬聚合匹配一個objectIds數組

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM