将变量传递给 MongoDB 视图 [英] Passing Variables to a MongoDB View

查看:58
本文介绍了将变量传递给 MongoDB 视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 MongoDB 中创建视图以避免不必要的返回.在文档中说聚合函数可以采用带有双美元符号的变量,考虑到这一点,我创建了一个视图,在本示例中应该采用一个变量来过滤 customerIds 并将结果分组以总结不同文档的付款.

i'm trying to make views in MongoDB to avoid unnecessary returns. In the documentation says that the aggregation functions can take variables with a double dollar sign, taking this in mind i have created a view that in this example should take one variable to filter customerIds and group the results to sum the payments of different documents.

示例:

db.createView(
  "viewName",
  "myCollection",
  [{
    $match: {  "customerId": "$$customerId", }
  },{
    $group: {
      _id: null,
      total: "$amount",
    }
  }]
)

视图创建正常,如果我在聚合函数中放置了一些有效的 customerId 可以正常工作,但我不知道如何执行视图并传递我的 customerID需要.

The view is created OK and if i put some valid customerId in the aggregation function that works ok, but i don't have the slightest idea how to execute the view and pass the customerID that i need.

有什么想法吗?在这种情况下,mongodb 文档对我没有帮助,我真的需要将其创建为视图,因为有许多应用程序将连接到此视图.

Any ideas? The mongodb documentation does not help me in this situation and i really need to create this as a view, since there are many applications that will connect to this view(s).

我试过:db.viewName.find({customerId: "some valid id"});

I have tried: db.viewName.find({customerId: "some valid id"});

推荐答案

您可以像访问集合一样访问它,例如我正在通过以下方式创建视图:

You can access it just like a collection, for example I am creating a view via:

db.runCommand({
  create: 'AuthorsView',
  viewOn: 'authors',
  pipeline: [{
    "$group": {
      "_id": "$email",
      "count": {
        "$sum": 1
      }
    }
  }]
})

因为这是一个现有的视图,所以我可以简单地做:

Since this is now an existing view I can simply do:

db.getCollection('AuthorsView').find({})

查看所有文档或添加更多参数到find

To see all the documents or to add more parameters to the find

不确定传递变量是什么意思,因为视图就像集合……您通过 find 对它们运行查询 &聚合.

Not sure what you mean by passing variables since views are just like collections ... you run queries against them via find & aggregate.

这篇关于将变量传递给 MongoDB 视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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