Home > Software engineering >  mongodb extract values from a double nested object
mongodb extract values from a double nested object

Time:06-25

My data has this structure:

[
  {
    name: 'parent1',
    children:{
      child1:{ age:12, isSomething: true },
      child2:{ age:13, isSomething: false },
      child3:{ age:12, isSomething: true }
    }
  },
  {
    name: 'parent2',
    children:{
      child4:{ age:12, isSomething: true },
      child5:{ age:15, isSomething: false }
    }
  },
  ...
]

each document has a field children (object) containing all children for that parent, where for each element the key is the child name, and the value is an object containing that child's properties.

All children names across all documents are unique (child1, child2, ...)

Problem:

I want to query documents based on children properties, like for example: I want to get all documents that contain a child with age 15 => returns "parent2"

Is there some wildcard to cover for the diffrent keys in children, something like this:

find({"children.*.age":15})

CodePudding user response:

You can use aggregation

db.collection.aggregate([
  {
    $set: {
      obj: { "$objectToArray": "$children" }
    }
  },
  {
    $set: {
      obj: {
        "$filter": {
          "input": "$obj",
          "cond": {
            $gte: [ "$$this.v.age", 15 ]
          }
        }
      }
    }
  },
  {
    $match: {
      obj: { $ne: [] }
    }
  },
  {
    $project: {
      name: 1
    }
  }
])

Working Mongo playground

  • Related