Taras Danylchenko
Taras Danylchenko

Reputation: 347

Sorting Multiple Array elements by field

Here is a MongoDB document records:

# OBJ 1
{
"UID":"3e87ca58-abcd-4444-9993-5555c07bf889",
"userId":"5c3cac81989a8469d435f3b2",
"title":"object1",
"latest":0
}

# OBJ 2
{
"UID":"3e87ca58-abcd-4444-9993-5555c07bf889",
"userId":"5c3cac81989a8469d435f3b2",
"title":"object1",
"latest":1
}

# OBJ 3
{
"UID":"3e87ca58-a013-4191-9993-0673c07bf77c",
"userId":"5c3cac81989a8469d435f3b2",
"title":"object2",
"latest":0
}

# OBJ 4
{
"UID":"3e87ca58-a013-4191-9993-0673c07bf77c",
"userId":"5c3cac81989a8469d435f3b2",
"title":"object2",
"latest":1
}

My goal is to find elements where $match: { 'userId' : "5c3cac81989a8469d435f3b2" },and field latest is greater than this field in the element with the same UID.
So i expect to get this result

[
 {
  "UID":"3e87ca58-abcd-4444-9993-5555c07bf889",
  "userId":"5c3cac81989a8469d435f3b2",
  "title":"object1",
  "latest":1
 },
 {
  "UID":"3e87ca58-a013-4191-9993-0673c07bf77c",
  "userId":"5c3cac81989a8469d435f3b2",
  "title":"object2",
  "latest":1
 }
]

Upvotes: 1

Views: 32

Answers (1)

Ashh
Ashh

Reputation: 46441

You can use below aggregation

db.collection.aggregate([
  { "$match": { "userId": "5c3cac81989a8469d435f3b2" }},
  { "$group": {
    "_id": "$UID",
    "latest": { "$max": "$latest" },
    "title": { "$max": "$title" },
    "userId": { "$first": "$userId" }
  }}
])

Upvotes: 1

Related Questions