deltaforce
deltaforce

Reputation: 534

How to query mongodb to fetch results based on values nested parameters?

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"
}

Upvotes: 1

Views: 66

Answers (1)

whoami - fakeFaceTrueSoul
whoami - fakeFaceTrueSoul

Reputation: 17915

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

Upvotes: 1

Related Questions