2016-09-05 3 views
2
[{ 
    "username":"user1", 
    "products":[ 
      {"productID":1,"itemCode":"CODE1"}, 
      {"productID":2,"itemCode":"CODE1"}, 
      {"productID":3,"itemCode":"CODE2"}, 
     ] 
}, 
{ 
    "username":"user2", 
    "products":[ 
      {"productID":1,"itemCode":"CODE1"}, 
      {"productID":2,"itemCode":"CODE2"}, 
     ] 
}] 

제품의 "itemCode"가 "CODE1"이되도록 "user1"에 대한 "products"의 모든 "productID"를 찾고 싶습니다.mongoDB 쿼리 중첩 배열의 문서를 찾으려면

mongoDB에서 어떤 쿼리를 작성해야합니까?

+0

내 업데이트 된 대답을 확인 –

+0

@ ReubenL. thnx, – Krisalay

답변

2

단일 조건 만 일치해야하는 경우 점 표기법으로 충분합니다. 몽고 쉘에서 는 :

db.col.find({"products.itemCode" : "CODE1", "username" : "user1"})

이 중첩 된 제품 객체가 "코드 1"itemCode을 갖는 모든 사용자를 반환합니다.

를 업데이트하는 것은 처음 사용자의 요구 사항에 명확하지 않았다하지만 그것을해야합니다.

각 제품을 별도의 항목으로 사용하려면 집계 프레임 워크를 사용해야합니다. 먼저 $unwind을 사용하여 배열의 항목을 분할 한 다음 조건에 $match을 사용합니다.

db.col.aggregate({$unwind: "$products"},{$match: { "username": "user1", "products.itemCode": "CODE1" } });

응답 : { "_id" : ObjectId("57cdf9c0f7f7ecd0f7ef81b6"), "username" : "user1", "products" : { "productID" : 1, "itemCode" : "CODE1" } } { "_id" : ObjectId("57cdf9c0f7f7ecd0f7ef81b6"), "username" : "user1", "products" : { "productID" : 2, "itemCode" : "CODE1" } }

+0

이것은 나에게 내가 원하지 않는 user2의 제품도 줄 것이다. – Krisalay

+0

아 나는 그 요구 사항을 놓쳤다. 그냥 추가 파라메타로 추가 할 수있다. –

+0

'db.col.find ({ "username": "user1", "products.itemCode": "CODE1"})' –

0

당신은있는 다음과 같은이 여러 필터를 필요 AND 상태지만 아무것도 없습니다 (가정 컬렉션 이름은 collection1됩니다)

db.collection1.find({"username":"user1", "products.itemCode" : "CODE1"}) 
+0

마지막으로 "username"을 " user1 " – Krisalay

+0

그런 경우에는 $ unwind –

관련 문제