0

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 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. Can you return id and new field name too and remove empty info? mongoplayground.net/p/A4bfCeaY6Op

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.