MongoDB查询基于嵌入式文档的计数 [英] MongoDB query based on count of embedded document

查看:157
本文介绍了MongoDB查询基于嵌入式文档的计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有:

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

如何过滤订单号大于5的订单?

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

推荐答案

您可以使用$ where运算符。

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

$的两个缺点是它不能使用索引,并且BSON对象必须转换为JavaScript对象,因为您正在集合中的每个文档上运行自定义JavaScript函数。

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.

所以,$对于大集合来说可能非常慢。但是,对于特别或很少运行查询,它是非常方便。如果你经常需要运行这样的查询,那么你应该遵循Bugai13的建议,因为你可以索引存储数组大小的键。

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.

这篇关于MongoDB查询基于嵌入式文档的计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆