Mongodb对特定记录而不是集合进行聚合查询 [英] Mongodb aggregate query on specific records instead of collection

查看:98
本文介绍了Mongodb对特定记录而不是集合进行聚合查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用汇总查询来查找使用此查询的所有客户的所有订单

i am using the aggregate query to find all orders for all customers using this query

> db.orders.aggregate([{ "$group":{ "_id":"$customer", "orders":{ "$sum": 1 }}}])
{ "_id" : "b", "orders" : 2 }
{ "_id" : "a", "orders" : 3 }

但现在,我不想在所有订单记录上运行此查询,而是只想在特定的订单集上运行它,此查询返回

but now instead of running this query on all orders records , i just want to run it on specific set of orders , which is returned by this query

   db.delivery.find({"status":"DELIVERED"},{order:1}).pretty() ,

这给了我

{ "order" : ObjectId("551c5381e4b0df29878547e1") } 
{ "order" : ObjectId("551c8f8ae4b0ab335af6ab91") } 
{ "order" : ObjectId("551ca7ede4b0ab335af6ab95") } 
{ "order" : ObjectId("551cb00fe4b0ab335af6ab98") } 
{ "order" : ObjectId("551cbe20e4b0df29878547ed") }
....and few more records

如何实现此功能,帮助

推荐答案

使用 $ match 运算符来过滤进入管道的文档。

Use the $match operator to filter the documents getting into your pipeline.

获取订单ID列表(用于 $ match 管道,该管道带有 $ in )使用 find() 光标的 map() 方法:

Get the list of order ids (to use in the $match pipeline with $in) by using the find() cursor's map() method:

var orderIds = db.delivery.find({"status": "DELIVERED"}).map(function(d){return d.order;});
db.orders.aggregate([
    { "$match": { "_id": { "$in": orderIds } } },
    { "$group": { "_id": "$customer", "orders": { "$sum": 1 } } }
])






对于MongoDB 3.2,使用 $ lookup 运算符,该运算符对同一数据库中未分片的集合进行左外部联接以过滤文档


For MongoDB 3.2, use the $lookup operator which does a left outer join to an unsharded collection in the same database to filter in documents from the "joined" collection for processing.

以下示例显示了如何在订单集合将订单中的文档与交付集合中的文档一起使用字段 order 来自交付集合:

The following example shows how you can run the aggregation operation on the orders collection joining the documents from orders with the documents from the delivery collection using the field order from the delivery collection:

db.orders.aggregate([
    {
        "$lookup": {
            "from": "delivery",
            "localField": "_id",
            "foreignField": "order",
            "as": "delivery_orders"
        }
    },
    { "$match": { "delivery_orders.status": "DELIVERED" } },    
    { "$group": { "_id": "$customer", "orders": { "$sum": 1 } } }
])

这篇关于Mongodb对特定记录而不是集合进行聚合查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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