Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to match a single property value in MongoDB

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading