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

半腔热情 提交于 2021-02-05 10:46:10

问题


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'}) ?


回答1:


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.



来源:https://stackoverflow.com/questions/56347376/how-to-find-specific-nested-objects-without-knowing-the-parent-key-in-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!