Mat.C
Mat.C

Reputation: 1429

How to find specific nested objects without knowing the parent key in mongodb

I'm using javascript and the mongoose module. I have an object like this

my_object = {
    ShopName: String,
    employees: [String],
    info: {
        NameEmployee_1: {
            age: String,
            work: String,
            city: String,
        },

        NameEmployee_2: {
            age: String,
            work: String,
            city: String,
        }
    } 

}

and i want find all the emoplyees that have a specific age but without knowing the name of the emplyee, is there a way for do this?

I know that you for example i can so something like this

db.collection.find({'info.Max': {$exists: true}})

for find all the Shops that have atleast one employee with name Max but what if i want all the Shops that have atleast one emplyee that has age 33

db.collection.find({'info.<name>.age': '33'}) ?

Upvotes: 0

Views: 1129

Answers (1)

Akrion
Akrion

Reputation: 18515

You can utilize the $objectToArray (mongoDB 3.4.4 and up), $filter and $project and get something like this:

db.collection.aggregate([
  {
    $project: {
      obj: {
        $objectToArray: "$info"
      }
    }
  },
  {
    $project: {
      _id: 0,
      obj: {
        $filter: {
          input: "$obj",
          as: "item",
          cond: {
            $eq: [
              "$$item.v.city",
              "NY"
            ]
          }
        }
      }
    }
  },
  {
    $project: {
      info: {
        $arrayToObject: "$obj"
      }
    }
  },
])

You can see it working here

The idea is to break the object to array, filter it and then convert that array back to object.

I filtered on city but I am sure you get the idea.

Upvotes: 2

Related Questions