简体   繁体   English

Mongodb:collection.find()中的动态查询对象

[英]Mongodb: Dynamic query object in collection.find()

I am working on a Node.js + MongoDB application. 我正在开发Node.js + MongoDB应用程序。 The application inserts some records in the MongoDB. 该应用程序在MongoDB中插入一些记录。 For example lets take below simple record: 例如让我们做下面的简单记录:

{
  "name": "Sachin",
  "age" : 11,
  "class": 5,
  "percentage": 78,
  "rating": 5
}

Now end user can set different rule for which they want to get the notification/alert when a specific condition is satisfied. 现在,最终用户可以设置满足特定条件时要获取通知/警报的不同规则。 For example we can have a rule like: 例如,我们可以有一个类似的规则:

1) Rule1: Generate notification/alert if "percentage" is less than 40 1)Rule1:如果“百分比”小于40,则生成通知/警报

In order to achieve this, I am using Replication and tailable cursor. 为了实现这一点,我使用了复制和可尾游标。 So whenever a new record gets added in the collection I get an record in the tailable cursor. 因此,无论何时在集合中添加新记录,我都会在可尾光标中获取一条记录。

coll = db.collection('oplog.rs');

options = {
    tailable: true,
    awaitdata: true,
    numberOfRetries: -1
};

var qcond = {'o.data.percentage':{$gt:40}};

coll.find(qcond, options, function(err, cur) {

    cur.each(function(err, doc) {

        //Perform some operations on received document like 
        //adding it to other collection or generating alert

    }); //cur.each

}); //find

Everything works fine till this point. 到目前为止,一切正常。

Now problem starts when enduser wants to add another rule at runtime say: 现在,当最终用户想要在运行时添加另一个规则时,问题就开始了:

2) Rule2: Generate notification/alert if "rating" is greater than 8 2)Rule2:如果“评级”大于8,则生成通知/警报

Now I would like to consider this condition/rule as well when querying the tailable cursor. 现在,我想在查询可尾游标时也考虑此条件/规则。 But the current cursor is already in a waiting state based on the conditions given as per Rule1 only. 但是当前光标仅根据Rule1给出的条件已经处于等待状态。

Is there any way to update the query conditions dynamically so that I can include conditions for Rule2 as well? 有没有办法动态地更新查询条件,以便我也可以包括Rule2的条件?

I tried searching but couldn't find a way to achieve this. 我尝试搜索,但找不到实现此目的的方法。

Does anyone have any suggestion/pointers to tackle this situation? 有没有人有任何建议/指针来解决这种情况?

No. You can't modify a cursor once it's open on the server. 否。一旦游标在服务器上打开,便无法修改。 You'll need to terminate the cursor and reopen it to cover both conditions, or open a second cursor to cover the second condition. 您需要终止游标并重新打开它以覆盖这两个条件,或者打开第二个游标以覆盖第二个条件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM