簡體   English   中英

在mongoDB中查詢以獲取具有不同值並最后添加的記錄

[英]Query in mongoDB to get records with different value and last added

我有這樣的人妖:

var messageSchema = system.mongoose.Schema({
    from: {
        type: system.mongoose.Schema.Types.ObjectId,
        required: true,
        ref: 'User'
    },
    to: {
        type: system.mongoose.Schema.Types.ObjectId,
        required: true,
        ref: 'User'
    },
    content: {
        type: String,
        required: true
    },
    createDate: {
        type: Date,
        default: Date.now
    }
});

如何創建查詢以僅獲取每個用戶的最后一條消息?

您可以使用聚合查詢

db.collection.aggregate([
    { "$sort" : { "createDate" : -1 } },
    {
        "$group" : {
            "_id" : "$from",
            "from" : { "$first" : "$from" },
            "to" : { "$first" : "$to" },
            "content" : { "$first" : "$content" },
            "createDate" : { "$first" : "$createDate" }
        }
    }
])

您可以在此處使用累加器。 最大蓄能器將組from再取最大值createdDate ,將返回最新的。

 db.messages.aggregate([
      {"$match":{}},
      {"$group":{
        "_id":"$from",
        "createdDate":{"$max":"$createdDate"},
        "content" : "$content"
        }
      },
      {"$sort":{"createdDate":-1}},{"$skip":0},{"$limit":10}],{})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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