Home > Enterprise >  MongoDB should report error when negative integer is used in dot notation?
MongoDB should report error when negative integer is used in dot notation?

Time:11-17

MongoDB allows to use dot notation to do queries on JSON sub-keys or array elements (see ref1 or ref2). For instance, if a is an array in the documents the following query:

db.c.find({"a.1": "foo"})

returns all documents in which 2nd element in the a arrary is the "foo" string.

So far, so good.

What is a bit surprissing in that MongoDB accepts using negative values for the index, e.g.:

db.c.find({"a.-1": "foo"})

That doesn't return anything (makes sense if it an unsupported syntax) but what I wonder if why MongoDB doesn't return error upon this operation or if it has some sense at the end. Documentation (as far as I've checked) doesn't provide any clue.

Any information on this is welcome!

CodePudding user response:

That is not an error. The BSON spec defines a key name as

Zero or more modified UTF-8 encoded characters followed by '\x00'. The (byte*) MUST NOT contain '\x00', hence it is not full UTF-8.

Since "-1" is a valid string by that definition, it is a valid key name.

Quick demo:

> db.test.find({"a.-1":{$exists:true}})
{ "_id" : 0, "a" : { "-1" : 3 } }

Playground

Also note how that spec defines array:

Array - The document for an array is a normal BSON document with integer values for the keys, starting with 0 and continuing sequentially. For example, the array ['red', 'blue'] would be encoded as the document {'0': 'red', '1': 'blue'}. The keys must be in ascending numerical order.

  • Related