简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM