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

前端 未结 1 536
走了就别回头了
走了就别回头了 2021-01-28 07:24

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

my_object = {
    ShopName: String,
    employees: [String],
    info: {
        NameEm         


        
相关标签:
1条回答
  • 2021-01-28 07:53

    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.

    0 讨论(0)
提交回复
热议问题