MongoDB query based on count of embedded document

前端 未结 4 429
一生所求
一生所求 2021-01-03 05:15

Suppose I have:

Order: {_id: ..., items: [...]}

How to filter orders which have item number greater than 5?

4条回答
  •  情话喂你
    2021-01-03 05:26

    You can use the $where operator.

    > db.orders.save({Order: {items: [1,2]}})                                                    
    > db.orders.save({Order: {items: [1,2,3]}})
    > db.orders.find({$where:function() { if (this["Order"]["items"].length > 2) return true; }})
    { "_id" : ObjectId("4d334c9102bcfe450ce52585"), "Order" : { "items" : [ 1, 2, 3 ] } }
    

    Two downsides of $where are that it can't use an index and the BSON object must be converted to a JavaScript object, since you are running a custom JavaScript function on every document in the collection.

    So, $where can be very slow for large collections. But, for ad hoc or rarely run queries, it's extremely handy. If you frequently need to run queries like this, then you should follow Bugai13's recommendation, since you can then index the key in which you store the array size.

提交回复
热议问题