Mongo - 查找具有特定条件的文档

时间:2018-04-12 16:16:34

标签: javascript mongodb mongoose

我有这个doc结构:

{
    "_id" : ObjectId("598c00090ec35f5dd3dc508a"),
    "type" : "Wear",
    "kind" : "Shoes",
    "brand" : "Free People",
    "article" : "6718_brown",
    "grander" : "m",
    "size" : {
        "39" : 1,
        "44" : 0,
        "45" : 6
    },
    "rsp" : 3400,
    "price" : 873,
    "createdAt" : ISODate("2017-08-10T06:41:13.294Z"),
    "images" : [ 
        "6718_bezhevye_!_1.jpg", 
        "6718_bezhevye_!_2.jpg", 
        "6718_bezhevye_!_3.jpg", 
        "6718_bezhevye_!_4.jpg", 
        "6718_bezhevye_!_5.jpg"
    ],
    "__v" : 0
}

我需要找到所有物品,女巫满足条件: size[key1] + size[key2] + size[key3] > 0。 请帮忙,我该怎么做?

3 个答案:

答案 0 :(得分:1)

您可以使用$addFields使用点表示法计算总和,然后使用$ match检查条件:

var key1 = "39";
var key2 = "44";
var key3 = "45";

db.col.aggregate([
    {
        $addFields: {
            sum: {
                $add: [ "$size." + key1, "$size." + key2, "$size." + key3 ]
            }
        }
    },
    {
        $match: {
            sum: {
                $gt: 0
            }
        }
    }
])

答案 1 :(得分:0)

您可以使用mapReduce

执行此操作
db.getCollection('products').mapReduce(
  function() {
    for (var key in this.size)
      emit(this._id, this.size[key]);
  },
  function(key, values) {
    return Array.sum(values);
  },
  {
    out: 'size_sum'
  }
)

然后得到结果

db.getCollection('size_sum').find({
  value: {
    $gt: 0
  }
})

答案 2 :(得分:0)

您可以使用objectToArray和sum

db.getCollection('collection').aggregate([
  { $project: { item: 1, sizes: { $objectToArray: "$size" }}},
  { $project:{count: { $sum: '$sizes.v' }}},
  { $match: { count: {$gt: 0}}}    
])