0

Question:

What I want is to loop over on the values of a field during the Mongo project,

For Example: Here is a small sample of my data

{
"_id": ObjectId(1),
"field1": {
   "key1":"value1",
   "key2":"value2"
} 
},
{
"_id": ObjectId(1),
"field1": {
   "key1":"value1",
   "key2":"value2",
   "key3":"value3"
}
} 
}

And my query is something like this:

MyDocument._get_collection().aggregate([
  # some match statement
  
  "$project": { 
     'customized_data': {
        '$ifNull': ['$field1.key1', "default_value"]
     }
  }
])

So my query is suitable just for one key. (key1 from field1). So how can I loop over "field1" values ("key1":"value1", "key2":"value2", "key3": "value3")and in order to a specific condition change output?

NOTE: I'm using the latest version of MongoDB4.2 so far

Phoenix
  • 3,996
  • 4
  • 29
  • 40
  • You can use the aggregation [$objectToArray](https://docs.mongodb.com/master/reference/operator/aggregation/objectToArray/index.html) operator - this returns a array. Then you can loop over the array using one of the aggregation array operators (like $map). – prasad_ Jun 30 '20 at 08:48
  • @prasad_ You know what makes your suggestion impossible, I want to compare each value separately. for example ```value1 greater than 1 and value2 greater than 2 and so on``` – Phoenix Jun 30 '20 at 08:57
  • And BTW thanks for your comment – Phoenix Jun 30 '20 at 08:57

0 Answers0