Home > database >  How to query a property of an object?
How to query a property of an object?

Time:12-26

{
  a: { 
   b: 1,
   c: 3
  }
}
db.col.aggregate([{$match: {a: /* some condition about b or c */ }}])
// e.g.
db.col.aggregate([{$match: {a: {b: { $eq: 5 }}}}])

So the idea is to specify some condition about the property of a field that is an object.

I am aware of this syntax:

db.col.aggregate([{$match: {"a.b": /* some condition about b */ }}])

But that is not the goal. The goal is the first syntax.

CodePudding user response:

The query

db.col.aggregate([{$match: {a: {b: { $eq: 5 }}}}])

Does not mean select every document where element b of element a is 5, it means select every document where element a is exactly {b: {$eq: 5}} (verbatim, i.e., that will not match {b: 5}) see https://mongoplayground.net/p/8l0BTpdDHTp

The query

db.col.aggregate([{$match: {"a.b": {$eq: 5}}}])

will match documents where a is an object with a field b that equals 5, even if there are other fields. See https://mongoplayground.net/p/mnZVGDaqYpz

If you need multiple criteria, you can list them separately at the top level like:

db.col.aggregate([{$match: {
                            "a.b": {$eq: 5},
                            "a.c": {$gte: 1}
                           }}])
  • Related