简体   繁体   中英

How to aggregate distinct array field in Mongodb

I have this schema

const GroupSchema = new Schema({
  id: { type: String },
  users: [{ type: Number }],
  status: { type: Boolean }
},
  {
    timestamps: true
  });

I try to aggregate distinct users value sorted by created date. Example

 {
    "users": [1111, 2222],
    "createdAt": {
        "$date": "2020-09-30T10:51:33.058Z"
    }
}
    {
        "users": [1111, 2222],
        "createdAt": {
            "$date": "2020-09-29T10:51:33.058Z"
        }
    }

I try with :

Group.aggregate([
        { "$sort": { "createdAt": -1 } },
        { $group : { _id : "$users" }}, //, created : { $last : "created" }
        { $match : { users : {$in : [1111] }  }}
    ])

I expect

 {
"users": [1111, 2222],
"createdAt": {
    "$date": "2020-09-30T10:51:33.058Z"
}
}

how can i solve? Thanks.

You can try,

  • $match your condition
  • $sort by createdAt date
  • $group by users array and get latest document in latestDoc
  • $replaceWith to replace latestDoc in root
db.collection.aggregate([
  { $match: { users: { $in: [1111] } } },
  { $sort: { createdAt: -1 } },
  {
    $group: {
      _id: "$users",
      latestDoc: { $first: "$$ROOT" }
    }
  },
  { $replaceWith: "$latestDoc" }
])

Playground

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