统计指定记录之前符合条件的记录
Count records matching criteria before a specified record
我在名为 "queue" 的集合中有一个用户列表。将用户添加到集合中时,对象如下所示:
{
"_id": ObjectID("5543cb95a02855d404823ec3"),
"id": "oBPLtOY2W6ChusMLAAAA",
"added": "2015-05-01T14:53:09-04:00",
"expiration": "",
"word": "",
"composed": false,
"active": false
}
现在,我要做的是计算集合中指定用户之前的记录数。但是,我只想统计符合特定条件的记录。
我可以像这样计算符合条件的记录:
db.collection("queue").count({
expiration: "",
word: "",
composed: false,
active: false
}, function(err, count) {
// Count = number of users that match the criteria
});
但是,我似乎无法弄清楚的是如何计算集合中仅出现在指定用户之前的那些记录。我能想到的唯一方法是遍历符合条件的记录列表,在每个循环中将计数器加 1,并在到达指定用户的 ID 时停止循环。
有更好的方法吗?
假设您有参考用户的 _id
值(我们称之为 reference_id
),以下应该有效:
db.collection("queue").count({
expiration: "",
word: "",
composed: false,
active: false,
_id: { "$lt": reference_id }
});
这将根据 _id
值搜索较早的用户。如果您要搜索具有更早 added
值的用户,请将查询更改为以下内容:
db.collection("queue").count({
expiration: "",
word: "",
composed: false,
active: false,
added: { "$lt": reference_date }
});
我在名为 "queue" 的集合中有一个用户列表。将用户添加到集合中时,对象如下所示:
{
"_id": ObjectID("5543cb95a02855d404823ec3"),
"id": "oBPLtOY2W6ChusMLAAAA",
"added": "2015-05-01T14:53:09-04:00",
"expiration": "",
"word": "",
"composed": false,
"active": false
}
现在,我要做的是计算集合中指定用户之前的记录数。但是,我只想统计符合特定条件的记录。
我可以像这样计算符合条件的记录:
db.collection("queue").count({
expiration: "",
word: "",
composed: false,
active: false
}, function(err, count) {
// Count = number of users that match the criteria
});
但是,我似乎无法弄清楚的是如何计算集合中仅出现在指定用户之前的那些记录。我能想到的唯一方法是遍历符合条件的记录列表,在每个循环中将计数器加 1,并在到达指定用户的 ID 时停止循环。
有更好的方法吗?
假设您有参考用户的 _id
值(我们称之为 reference_id
),以下应该有效:
db.collection("queue").count({
expiration: "",
word: "",
composed: false,
active: false,
_id: { "$lt": reference_id }
});
这将根据 _id
值搜索较早的用户。如果您要搜索具有更早 added
值的用户,请将查询更改为以下内容:
db.collection("queue").count({
expiration: "",
word: "",
composed: false,
active: false,
added: { "$lt": reference_date }
});