0

Till now, I had believe that the order of keys in query does not matter until I encountered the following case :

Let's say there's a collection with documents and you need to find just one that belongs to a certain group. The following query will fail to fetch document with an _id pFkpqenxxbiFFtzrd. Instead, it will fetch 2SYzj829FKnezgX3b

db.getCollection('Facilities').findOne({_id: "pFkpqenxxbiFFtzrd", _id: {$in: [ '2SYzj829FKnezgX3b', 'pFkpqenxxbiFFtzrd', 'Znsbs5Rzr6DopZmro' ]}})

While this one will do it :

db.getCollection('Facilities').findOne({_id: {$in: [ '2SYzj829FKnezgX3b', 'pFkpqenxxbiFFtzrd', 'Znsbs5Rzr6DopZmro' ]}, _id: "pFkpqenxxbiFFtzrd"})

The question is why?

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
Le garcon
  • 7,197
  • 9
  • 31
  • 46
  • Duplicate property names are not allowed, use a single `$in` for all IDs or `$or` instead. – str May 08 '18 at 08:53
  • Hardly weird, but certainly invalid and it's nothing to do with MongoDB anyway but basic rules of JavaScript objects. Cannot have the same key. – Neil Lunn May 08 '18 at 08:53
  • 1
    What you are trying to do would actually be an `$and`, but it does not really make sense and should be an `$or`, but if you mean that then simply add the item to the `$in`. You simply cannot have different conditions on the same key because JavaScript objects don't allow that. That's what the "array" operators are actually for. – Neil Lunn May 08 '18 at 09:02

0 Answers0