skip to Main Content

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)?

2

Answers


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

    Login or Signup to reply.
    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
            ]
          }
        }
      }
    ])
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search