当字段等于true时,计算子数组项

时间:2017-06-21 04:26:24

标签: mongodb mongoose mongodb-query

我需要帮助从数组空间中获取计数。我需要得到可用空间的数量。我尝试了多个查询,并尝试将计数推送到回调对象。喜欢这个

props.map( p => {
            var count = 0;
            for(var i = 0; i < p.spaces.length; ++i){
                if(p.spaces[i]['available'] == true)
                    count++;
            }
            p.push(""); //I dont know how to add the counts if this is a valid option
            console.log(count);
        });

    {
    "_id" : ObjectId("593a01b4b9ab7204b0336e60"),
    "name" : "Test1",
    "serie" : "MC-016-04",
    "created_at" : ISODate("2017-06-09T02:02:28.759Z"),
    "spaces" : [ 
        {
            "available" : false,
            "size" : "12",
            "dimensions" : "200",
            "local" : "Test 1",
            "_id" : ObjectId("594434b4aec46311043db2eb")
        }, 
        {
            "available" : true,
            "size" : "36",
            "dimensions" : "1200",
            "name" : "Test 7",
            "_id" : ObjectId("594434f6760a76110efc216e")
        }, 
        {
            "available" : true,
            "size" : "36",
            "dimensions" : "1200",
            "name" : "Test 2",
            "_id" : ObjectId("5944360ff249971142c5dd0f")
        }
     ]
   }

结果应该是这样的:

{
        "_id" : ObjectId("593a01b4b9ab7204b0336e60"),
        "name" : "Test1",
        "serie" : "MC-016-04",
        "created_at" : ISODate("2017-06-09T02:02:28.759Z"),
        "spaces" : [ 
            {
                "available" : false,
                "size" : "12",
                "dimensions" : "200",
                "local" : "Test 1",
                "_id" : ObjectId("594434b4aec46311043db2eb")
            }, 
            {
                "available" : true,
                "size" : "36",
                "dimensions" : "1200",
                "name" : "Test 7",
                "_id" : ObjectId("594434f6760a76110efc216e")
            }, 
            {
                "available" : true,
                "size" : "36",
                "dimensions" : "1200",
                "name" : "Test 2",
                "_id" : ObjectId("5944360ff249971142c5dd0f")
            }
         ],
        "availableSpaces" : 2
}

1 个答案:

答案 0 :(得分:0)

要使用availableSpaces获取数据,您可以在$size查询中使用$filteraggregate

db.collectionName.aggregate([
  {"$match": {}}, // match condition here
  {"$project": {
    "name" : 1,
    "serie" : 1,
    "created_at" : 1,
    "spaces": 1,
    "availableSpaces": {
      $size: {
        "$filter": {
          input: "$spaces",
          as: 'space',
          cond: '$$space.available' // for Boolean if not Boolean then you should use like: cond: {$eq: ['$$space.available', 'true']}  
        }
      }
    }
  }}
])