【问题标题】:MongoDB query - if value appears in array x timesMongoDB 查询 - 如果值出现在数组 x 次
【发布时间】:2014-06-26 06:18:06
【问题描述】:
{
  "_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' }

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

编辑 所以要增加一些乐趣。我更新了我的模式,所以我需要把它变成一个条件。 if limit = 'unlimited' { return record } if limit = 'limited' { 仅当数组少于 2 个值时才返回 = '1f7f5f96be3a'

【问题讨论】:

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


    【解决方案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 和 last $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"}]}}
    

    【讨论】:

    • 非常感谢,让我离得更近了。所以为了增加一些乐趣......我更新了我的模式,所以我需要把它变成一个条件。 if limit = 'unlimited' { return record } if limit = 'limited' { 仅当数组的值少于 2 个时才返回 = '1f7f5f96be3a' 任何这样做的人。基本上你做了什么,但有条件?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多