1

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
 }
]
1
  • you probably need to use a group by using the field the field "latest" and then sort by that same field (desc) Commented Jan 14, 2019 at 16:47

1 Answer 1

1

You can use below aggregation

db.collection.aggregate([
  { "$match": { "userId": "5c3cac81989a8469d435f3b2" }},
  { "$group": {
    "_id": "$UID",
    "latest": { "$max": "$latest" },
    "title": { "$max": "$title" },
    "userId": { "$first": "$userId" }
  }}
])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.