Home > Net >  MongoDB - How to match a single property value
MongoDB - How to match a single property value

Time:09-13

Suppose a collection contains the following 3 documents:

[
  { "_id": 1, "prop": 1 },
  { "_id": 2, "prop": 4 },
  { "_id": 3, "prop": [1, 2, 3] }
] 

The query { $match: { prop: 1 } } returns 2 documents, namely 1 and 3. I would have expected it to only return 1.

  1. Is this behaviour documented somewhere or is it a bug?
  2. How could one formulate the query to mean strict equality (as opposed to equality or array-contains)?

CodePudding user response:

I think that MongoDB will always try to match against both scalars and arrays, unless you explicitly rule out the latter:

{ $match : { prop : { $eq : 1, $not: { $type : 'array' } } } }

It doesn't seem to be explicitly documented, but it's implied in the documentation because the syntax for querying scalars for a particular value is the same as the syntax for querying arrays.

CodePudding user response:

  1. I believe the query returns the document with _id: 3 is due to Query an Array for an Element.

The document with _id: 3 will be fulfilled as there is an element matched in the array.

  1. To force strict equality match, I would suggest to provide the aggregation operator in your query, which will include the checking of type.
db.collection.aggregate([
  {
    $match: {
      $expr: {
        $eq: [
          "$prop",
          1
        ]
      }
    }
  }
])

CodePudding user response:

Did you try db.collection.find(query, projection, options) ?

I solved this issue by better understanding the find function from here: https://www.mongodb.com/docs/manual/reference/method/db.collection.find/#mongodb-method-db.collection.find

  • Related