MongoDB:匹配嵌套数组元素的计数 [英] MongoDB: Count of matching nested array elements

查看:48
本文介绍了MongoDB:匹配嵌套数组元素的计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的父子对象作为文档存储在 MongoDB 中.一些简单的东西,比如 Order/OrderItems.(订单有一个 OrderItem 数组)

I've got a simple parent child object stored as a document in MongoDB. Something simplistic like Order/OrderItems. (Order has an array of OrderItem)

我想要做的是查询满足一组条件的订单项目的数量.

What I'd like to do is query for a count of Order Items where they meet a set of criteria.

示例:在订单999"中找出数量为 3 的订单商品数量.

Example: In Order "999" find out how many order items had a quantity of 3.

db.collection.find( {OrderId:999, "OrderItems.QuantityOrdered":3} ).count();

这个查询的工作方式是它返回1",因为如果它匹配数组中的至少一个 OrderItem,它将返回匹配的订单数.

The way this query works is it returns "1" because if it matches at least one OrderItem inside the array it will return the count of Orders matched.

如何查询匹配的OrderItems"数量?:

How can I query for how many "OrderItems" matched?:

推荐答案

没有直接的方法用嵌入的文档返回这种计数.使用这种临时计数,最好的办法是返回文档并从应用程序进行计数.

There's no direct way of return this sort of count with an embedded document. With this sort of ad-hoc count, your best bet is to return the document and do the count from the application.

如果你想对大量订单执行这种计数,你可以使用map-reduce,它将结果输出到一个新的集合中.

If you want to perform this kind of count for a large number of orders, you could use map-reduce, which will output the results to a new collection.

这篇关于MongoDB:匹配嵌套数组元素的计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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