1

I have nested object of objects. Each document in collection looks like this:

{
   anything: "whatever",
   something: {
      // find inside of these document
      a: { getThis: "wow" },
      b: { getThis: "just wow" },
      c: { getThis: "another wow" }
   }
}

I would like to find in every getThis from each document in something.


For example I would like to find document which has getThis: "wow".

I've tried to use something like wildcard with *:

{"something.*.getThis": "wow" }

I've also tried $elemMatch but it seems it works only with array;

{ something: { $elemMatch: { getThis: "wow" } } }

1 Answer 1

1

You can try using $objectToArray,

  • $addFields to convert something to array in somethingArr
  • $match condition getThis is wow or not
  • $project to remove somethingArr
db.collection.aggregate([
  {
    $addFields: {
      somethingArr: { $objectToArray: "$something" }
    }
  },
  { $match: { "somethingArr.v.getThis": "wow" } },
  { $project: { somethingArr: 0 } }
])

Playground


Second possible way

  • $filter input something as array, convert using $objectToArray
  • filter will check condition getThis is equal to wow or not
db.collection.aggregate([
  {
    $match: {
      $expr: {
        $ne: [
          [],
          {
            $filter: {
              input: { $objectToArray: "$something" },
              cond: { $eq: ["$$this.v.getThis", "wow"] }
            }
          }
        ]
      }
    }
  }
])

Playground

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

Comments

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.