2017-01-25 1 views
-1

나는 주전자로 작업 중이며 몇 개의 예상 값을 가진 항목의 수를 계산해야합니다 (내부 배열에 두 개 이상의 필드가 있음). 예를 들어

:

{ 
    "_id":"HY1406", 
    "accounts": [ 
     { 
      "should_exist" : 1, 
      "endpoint" : "0_AD", 
      "exists" : 0, 
      "short_login" : "TB6" 
     }, 
     { 
      "should_exist" : 1, 
      "endpoint" : "0_AD", 
      "exists" : 0, 
      "short_login" : "TB7" 
     }, 
     { 
      "should_exist" : 1, 
      "endpoint" : "0_AD", 
      "exists" : 0, 
      "short_login" : "TB8" 
     } 
    ] 
} 

나는 계정이 "sould_exist" = 1 AND "exists" = 0를 가진 AT LEAST을 얼마나 많은 문서를 계산해야합니다.

MongoDB 쿼리로 어떻게 수행 할 수 있습니까?

+0

예상되는 결과는 무엇을 사용하여 필터를 쓰기? – styvane

+0

코드, 이미 시도한 것을 보여주십시오. –

+2

db.collection.find ({ "accounts.should_exist": 1, "accounts.exists": 0}) count() – mmu36478

답변

0

$elemMatch을 사용하여 배열의 포함 된 문서 기준을 모두 일치시켜야합니다. find()으로 커서를 가져오고 count()을 호출하십시오.

db.collection.find({ 
    accounts : { 
     $elemMatch : {should_exist : 1, exists : 0} 
    } 
}).count() 

또는 count()

db.collection.count({ 
    accounts : { 
     $elemMatch : {should_exist : 1, exists : 0} 
    } 
}) 

내부 또는 집계

db.collection.aggregate([ 
{ 
    $match : { 
     accounts : { 
      $elemMatch : {should_exist : 1, exists : 0} 
     } 
    } 
}, 
{ 
    $group : { 
     _id : "foo", 
     count : {$sum : 1} 
    } 
} 
]) 
+0

흥미로운 것 같습니다. 카테고리 1 : "sould_exist"= 1 AND "exists"= 0 그리고 카테고리 2 : "sould_exist"= 1 AND "exists"= 1 결과는 다음과 같습니다 : { "_id ": 1.0,"numCat1 ": 2,"numCat2 ": 7} 어떻게 이러한 쿼리를 수행 할 수 있습니까? – sifokl

+0

그 질문에 게시 한 내용과 완전히 다릅니다. * "sould_exist"= 1이고 "exists"= 0 인 계정을 가진 문서가 몇 개인 지 계산해야합니다. – ares