1

I am working with MongoDB for the first time.

I have a collection whose each document is roughly of the following form in MongoDB:

{
   "name":[
      {
         "value":"abc",
         "created_on":"2020-02-06 06:11:21.340611+00:00"
      },
      {
         "value":"xyz",
         "created_on":"2020-02-07 06:11:21.340611+00:00"
      }
   ],
   "score":[
      {
         "value":12,
         "created_on":"2020-02-06 06:11:21.340611+00:00"
      },
      {
         "value":13,
         "created_on":"2020-02-07 06:11:21.340611+00:00"
      }
   ]
}

How will I form a query so that I get the latest updated values of each field in the given document. I went through Query Embedded Documents, but I wasn't able to figure out how It is.

My expected output is:

{
    "name": "xyz",
    "score": "13"
}
4
  • Please show the expected output and the field with which you want max value Commented Feb 7, 2020 at 6:26
  • @deltaforce : I guess latest values be always pushed to name & score arrays ? or can the latest values act as updates to the existing record rather than adding new object to array ? Commented Feb 7, 2020 at 6:54
  • @whoami : Iatest values will always be pushed to name & score arrays as I've to maintain update history of each name & score. Commented Feb 7, 2020 at 7:00
  • 1
    @whoami: I'm still working on it. Will accept as soon as I test and validate it soon :) Commented Feb 11, 2020 at 3:58

1 Answer 1

1

If you always do push new/latest values to arrays name & score, then you can try below query, it would get last element from array as in general new/latest values will always be added as last element in an array :

db.collection.aggregate([
    { $addFields: { name: { $arrayElemAt: ['$name', -1] }, score: { $arrayElemAt: ['$score', -1] } } },
    { $addFields: { name: '$name.value', score: '$score.value' } }])

Test : MongoDB-Playground

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.