Skip to content Skip to sidebar Skip to footer

Collect Distinct Field Names At Nested Level With Specific Condition

I have problem statement, in which i need all the field names at child level of 'config.first.second' where include field is true at least once. Here is my mongo collection object

Solution 1:

You can run with mapReduce:

db.collection.mapReduce(
  function() {
    Object.keys(this.config.first.second)
      .filter( k =>this.config.first.second[k].include === "true" )
      .forEach(k =>emit(k,1) );
  },
  function() { },
  { 
    "out": { "inline": 1 },

  }
)['results'].map( d => d._id )

If you have MongoDB 3.4 then you can use .aggregate():

db.collection.aggregate([
  { "$project": {
    "field": {
      "$filter": {
        "input": { "$objectToArray": "$config.first.second" },
        "as": "f",
        "cond": { "$eq": [ "$$f.v.include", "true" ] }
      }
    }
  }},
  { "$unwind": "$field" },
  { "$group": { "_id": "$field.k" } }
]).toArray().map(d => d._id)

Returns:

[
    "field1",
    "field3",
    "field7"
]

Post a Comment for "Collect Distinct Field Names At Nested Level With Specific Condition"