2

I have to query my mongoDB collection by type.
Suppose I have these two documents of hello collection:

{
        "_id" : ObjectId("56684ee0f597654b99d0d636"),
        "name" : "Scrooge",
        "surname" : "McDuck",
        "address" : {
                "road" : "Money Bin",
                "number" : 19
        },
        "hobbies" : [
                "money",
                "food",
                "cooking"
        ]
}
{
        "_id" : ObjectId("66684ee0f597654b99d0d636"),
        "name" : "Mickey",
        "surname" : "Mouse",
        "address" : {
                "road" : "Topolinia",
                "number" : 34
        },
        "hobbies" : [
                "minnie",
                "cheese"
        ]
}

Now, if I query by array type:

db.hello.find({hobbies: {$type: 4 }})

I don't have any documents in output. As you can see here 4 is the number of array type.

1
  • It is not so obvious but the documentation is clear: For documents where field is an array, $type returns documents in which at least one array element matches a type passed to $type. Commented Mar 11, 2020 at 9:14

4 Answers 4

4

This is the expected behaviour. You can simply do this using the "dot notation" and the $exists operator

db.hello.find({ 'hobbies.0': { '$exists': true } } )

Another way to do this is by using aggregation and the $isArray operator available in MongoDB 3.2. But this is less efficient because $redact does a collection scan.

 db.hello.aggregate([ 
    { "$redact": { 
        "$cond": [
             { $isArray: "$hobbies" }, 
             "$$KEEP", 
             "$$PRUNE" 
        ]
    }}
])
Sign up to request clarification or add additional context in comments.

Comments

2

According to the docs, you need to use a where clause:

db.hello.find( { $where : "Array.isArray(this.hobbies)" } );

1 Comment

No you don't need $where
2

You need to use where clause. Refer below syntax:
db.hello.find( { $where : "Array.isArray(this.hobbies)" } );

Comments

1

Look at https://docs.mongodb.org/v3.0/reference/operator/query/type/#arrays

Arrays

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.

When you query on the hobbies field, the query will actually try to match the elements inside the field because it's an array. So instead you can do:

db.hello.find({ $where: 'Array.isArray(this.hobbies)' });

But it won't be very efficient and won't use an index.

1 Comment

You don't need to drop to $where

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.