2016-06-09 93 views
0
{ 
     _id:1, members: [ 
     { 
      name:"John", 
      status:"A" 
     }, 
     { 
      name:"Alex", 
      status:"D" 
     }, 
     { 
      name:"Jack", 
      status:"A" 
     }, 
     { 
      name:"Robin", 
      status:"D" 
     } 
    ]} 

Channel document计算数组中相同类型的元素mongodb

现在我需要count成员数组中的所有元素,其中status equal to 'A'

例如上述文档有2个成员status 'A'

我该如何做到这一点?

+0

'db.collectionname.find({ “members.status”: “A”})。COUNT()' –

回答

0

这里是您的JSON文件

{ 
    "_id" : ObjectId("575915653b3cc43fca1fca4c"), 
    "members" : [ 
     { 
      "name" : "John", 
      "status" : "A" 
     }, 
     { 
      "name" : "Alex", 
      "status" : "D" 
     }, 
     { 
      "name" : "Jack", 
      "status" : "A" 
     }, 
     { 
      "name" : "Robin", 
      "status" : "D" 
     } 
    ] 
} 

而且要将所有元素的个数在成员数组,其中 状态等于“A”。

你一定要试试这一个,找出你的计数

db.CollectionName.aggregate([{ 
    "$project": { 
     "members": { 
      "$filter": { 
       "input": "$members", 
       "as": "mem", 
       "cond": { 
        "$eq": ["$$mem.status", "A"] 
       } 
      } 
     } 
    } 
}, { 
    "$project": { 
     "membersize": { 
      "$size": "$members" 
     } 
    } 
}]).pretty() 

而且你发现你的答案是这样{ “_id”: 的ObjectId( “575915653b3cc43fca1fca4c”),“membersize “:2}

试试这个旧版本......

db.CollectionName.aggregate([{"$unwind":"$members"},{"$match":{"members.status":"A"}},{"$group":{_id:"$_id","memberscount":{"$sum":1}}}]).pretty() 
{ "_id" : ObjectId("575915653b3cc43fca1fca4c"), "memberscount" : 2 } 
1

您可以使用mongodb-count来达到预期的效果。

返回将匹配find()查询的文档数。 db.collection.count()方法不执行find()操作,而是计数并返回与查询匹配的结果数。

所以您的查询就会

var recordcount = db.collName.count({"members.status":"A"}); 

现在recordCount将是匹配{"members.status":"A"}查询记录数。

-1

这里是您的JSON文件

{ 
    "_id" : ObjectId("575915653b3cc43fca1fca4c"), 
    "members" : [ 
     { 
      "name" : "John", 
      "status" : "A" 
     }, 
     { 
      "name" : "Alex", 
      "status" : "D" 
     }, 
     { 
      "name" : "Jack", 
      "status" : "A" 
     }, 
     { 
      "name" : "Robin", 
      "status" : "D" 
     } 
    ] 
} 

而且要将所有元素的个数在成员数组,其中 状态等于 'A'。

你一定要试试这一个,找出你的计数

db.CollectionName.aggregate([{ 
    "$project": { 
     "members": { 
      "$filter": { 
       "input": "$members", 
       "as": "mem", 
       "cond": { 
        "$eq": ["$$mem.status", "A"] 
       } 
      } 
     } 
    } 
}, { 
    "$project": { 
     "membersize": { 
      "$size": "$members" 
     } 
    } 
}]).pretty() 

而且你发现你的答案是这样{ “_id”: 的ObjectId( “575915653b3cc43fca1fca4c”),“membersize “:2}

+0

谢谢,但我的MongoDB的版本是3.0.7和更新can'nt。那么这个mongodb版本还有其他解决方案吗? – pankaj005

+0

试试这个然后db.CollectionName.aggregate([{“$ unwind”:“$ members”},{“$ match”:{“members.status”:“A”}},{“$ group”:{ _id: “$ _ ID”, “memberscount”:{ “$总和”:1}}}])相当() –