1

I'm having difficulty understanding how arrays work in the Mongo shell. It seems that whenever I create an array the "typeof" is still object and I when I try to run the following:

db.collection.find(test: {$type : 4})

I get no results, even though previously I had inserted an array into the collection using the following:

db.collection.insert({"test" : ["1", "2","3]})

Is this something I am not understanding about JSON or BSON? Are arrays still objects and if so how do you test if the object you have is an array? Ultimately I am hoping to split some strings in my database into arrays of strings but when I tested the type afterwards to ensure my code was working I was confused to find no type = array, even though they appear to be there when I look at findOne()!

2 Answers 2

1

From the docs:

When applied to arrays, $type matches any inner element that is of the specified type. Without projection this means that the entire array will match if any element has the right type. With projection, the results will include just those elements of the requested type.

So your query:

db.collection.find({test: {$type : 4}})

will not match any documents because your field test is an array whose elements are strings. What you need is essentially

db.collection.find({ $where : "Array.isArray(this.test)" })

which will use $where to list all documents containing a test field that is an array.

Sign up to request clarification or add additional context in comments.

Comments

0

A good way to test for an array type that doesn't use $where is to query for the existence of a first element, or for an empty array:

> db.test.drop()
> db.test.insert({ "a" : [] })
> db.test.insert({ "a" : 4 })
> db.test.insert({ "a" : [4] })
> db.test.find({ "$or" : [{ "a" : [] }, { "a.0" : { "$exists" : true } }] }, { "_id" : 0 })
{ "a" : [ ] }
{ "a" : [ 4 ] }

1 Comment

Thanks @wdberkeley this is also something I'll use in future

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.