2014-10-05 32 views

回答

0

的一種方式,是利用$where運營商在find()查詢:

// pass a function to the `$where` operator, to pick records 
// if they meet the desired condition. 
db.collection.find({ 
    $where : function() { 
     return (this.uses.length < this.useLimit || this.useLimit == -1); 
    } 
}) 

或全光照克aggregation管道,

  • 項目爲每個文檔字段isValid,以其值解析 到truefalsetrue,如果條件符合,則返回false
  • 下一步是將所有文檔與isValid 屬性的值匹配,值爲true
  • 最後,$project運營商投射除 isValid以外的字段。

如下,

db.collection.aggregate([ { 
    $project : { 
     "uses" : 1, 
     "useLimit" : 1, 
     "isValid" : { 
      $cond : [ { 
       $or : [ { 
        $gte : [ "$useLimit", { 
         $size : "$uses" 
        } ] 
       }, { 
        $eq : [ "$useLimit", -1 ] 
       } ] 
      }, true, false ] 
     } 
    } 
}, { 
    $match : { 
     "isValid" : true 
    } 
}, { 
    $project : { 
     "uses" : 1, 
     "useLimit" : 1 
    } 
} ])