2

What behavior is expected in this case? Will mongo treat empty array as null/undefined and include it into sparse index or if array is empty, document won't be indexed?

1 Answer 1

1

Empty arrays are not treated the same as null in MongoDB. As you can see in the following code from the Mongo shell, a sparse index finds the empty array as an empty array as opposed to as null.

> c = db.docs
test.docs
> c.insert({a : []})
> c.ensureIndex({a : 1}, {sparse: true})
> c.find({a : []}).count()
1
> c.find({a : null}).count()
0

As with most interesting questions about MongoDB, using explain will provide a wealth of info. For example, you can see that the test actually uses the index and that the boundaries of the index are null and [], demonstrating their unique treatment.

> c.find({a : null}).explain()
{
    "cursor" : "BtreeCursor a_1",
    "isMultiKey" : false,
    "n" : 0,
    "nscannedObjects" : 0,
    "nscanned" : 0,
    "nscannedObjectsAllPlans" : 0,
    "nscannedAllPlans" : 0,
    "scanAndOrder" : false,
    "indexOnly" : false,
    "nYields" : 0,
    "nChunkSkips" : 0,
    "millis" : 0,
    "indexBounds" : {
        "a" : [
            [
                null,
                null
            ]
        ]
    },
    "server" : "new-host.home:27017"
}
> c.find({a : []}).explain()
{
    "cursor" : "BtreeCursor a_1 multi",
    "isMultiKey" : false,
    "n" : 1,
    "nscannedObjects" : 1,
    "nscanned" : 1,
    "nscannedObjectsAllPlans" : 1,
    "nscannedAllPlans" : 1,
    "scanAndOrder" : false,
    "indexOnly" : false,
    "nYields" : 0,
    "nChunkSkips" : 0,
    "millis" : 0,
    "indexBounds" : {
        "a" : [
            [
                null,
                null
            ],
            [
                [ ],
                [ ]
            ]
        ]
    },
    "server" : "new-host.home:27017"
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.