MongoDB查询 - 如果值出现在数组x次中

时间:2014-06-25 19:33:08

标签: node.js mongodb mongodb-query aggregation-framework

{
  "_id": ObjectId("53ab1d2c256072374a5cc63f"),
  "title": "10% Off",
  "endDate": "2015-05-08",
  "limit" : "limited",
  "redemptions": [
    "1f7f5f96be3a",
    "kf40vksk03ps"
  ]
}
{
  "_id": ObjectId("53ab1d2c25607sfdgs74a5cc63f"),
  "title": "20% Off",
  "endDate": "2015-06-07",
  "limit" : "unlimited",
  "redemptions": [
    "1f7f5f96be3a",
    "1f7f5f96be3a",
    "kf40vksk03ps"
  ]
}

故事:一个人可以兑换优惠券2次。 2次后,不要退货。 如何检查值是否小于2次?

希望它像以下一样简单:

{ 'redemptions' : { $exists: true }, $where : 'this.redemptions.$.1f7f5f96be3a.length < 2' }

如何计算数组中特定值的次数并进行比较呢?

修改 所以要增加一些乐趣。我更新了我的架构,所以我需要把它放到有条件的。如果limit = 'unlimited' {return record} if limit = 'limited' {仅当数组少于2个值时返回='1f7f5f96be3a'

1 个答案:

答案 0 :(得分:1)

您可以使用聚合框架做您想做的事情:

db.collection.aggregate([
    /* find only documents that have redemption key */
    { $match : { redemptions : { $exists: true }}},
    /* unwind the redemptions array so we can filter documents by coupons */
    { $unwind : "$redemptions" },
    /* filter only coupons you're looking for */
    { $match : { redemptions : "1f7f5f96be3a"}},
    /* group the documents back so we can calculate the count */
    { $group : { _id : "$_id",
                 title : { $first : "$title" },
                 endDate : { $first : "$endDate" },
                 count :  {$sum : 1 }}},
    /* finally, count the documents that have less than 2 coupons */
    { $match : { count : { $lt :2 }}}
]);

编辑:

您只需要更改$ group和最后$ match阶段:

{ $group : { _id : "$_id",
            title : { $first : "$title" },
            endDate : { $first : "$endDate" },
            limit : { $first : "$limit" },
            count :  {$sum : 1 }}},
/* finally, count the documents that have less than 2 coupons 
   or have limit "unlimited */
{ $match : { $or : [{ count : { $lt :2 }}, {limit : "unlimited"}]}}