简体   繁体   English

在mongoDB中查询以获取具有不同值并最后添加的记录

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

I have shema like this: 我有这样的人妖:

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
    }
});

How can I create query to get just last message from each user? 如何创建查询以仅获取每个用户的最后一条消息?

You can use aggregation query for it 您可以使用聚合查询

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

You can use Accumulator here. 您可以在此处使用累加器。 Max accumulator will group by from and then take maximum value of createdDate , which will return latest. 最大蓄能器将组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