Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find MongoDB object using value of another field

I recently found difficulty in finding an object stored in a document with its key in another field of that same document.

{
    list : {
        "red" : 397n8,
        "blue" : j3847,
        "pink" : 8nc48,
        "green" : 983c4,
    },
    result : [
                { "id" : 397n8, value : "anger" },
                { "id" : j3847, value : "water" },
                { "id" : 8nc48, value : "girl" },
                { "id" : 983c4, value : "evil" }
             ]
    }
}

I am trying to get the value for 'blue' which has an id of 'j3847' and a value of 'water'.

db.docs.find( { result.id : list.blue }, { result.value : 1 } );

# list.blue would return water
# list.pink would return girl
# list.green would return evil

I tried many things and even found a great article on how to update a value using a value in the same document.: Update MongoDB field using value of another field which I based myself on; with no success... :/

How can I find a MongoDB object using value of another field ?

like image 888
samland Avatar asked Dec 14 '25 05:12

samland


1 Answers

You can do it with the $filter operator within mongo aggregation. It returns an array with only those elements that match the condition:

db.docs.aggregate([
  {  
    $project: {
      result: {
        $filter: {
          input: "$result", 
          as:"item", 
          cond: { $eq: ["$list.blue", "$$item.id"]}
        }
      }
    }
  }
])

Output for this query looks like this:

{ 
  "_id" : ObjectId("569415c8299692ceedf86573"), 
  "result" : [ { "id" : "j3847", "value" : "water" } ] 
}
like image 74
Volodymyr Synytskyi Avatar answered Dec 16 '25 06:12

Volodymyr Synytskyi