Query by array type - MongoDB

不羁岁月 提交于 2019-12-20 04:40:23

问题


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:


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" 
        ]
    }}
])



回答2:


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

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



回答3:


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




回答4:


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.



来源:https://stackoverflow.com/questions/34183723/query-by-array-type-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!