2014년 11월 29일 토요일

how read a particular document from a array

Hi all,

for eg:
{
   "customer" : {
      "addresses" : {
         "address" : [
            {
               "city" : "bang",
               "streetNo" : 123
            },
            {
               "city" : "hyd",
               "streetNo" : 321
            }
         ]
      },
      "custId" : "123"
   }
}
 and i want to read a document from address array, which  "city" : "bang" so how to read??



Use projection with either positional or $elemMatch operator.



i used positional and $elemMatch operator but it is selecting all documents from array but not particular document of a array then what i will do



Then you didn't use the projection operator correctly.

Maybe you should provide the actual query that you used, and the result you got.   Include the result you expected.  It's very hard to guess what might be going wrong when you don't provide any details.



for eg:
{
   "customer" : {
      "addresses" : {
         "address" : [
            {
               "city" : "bang",
               "streetNo" : 123
            },
            {
               "city" : "hyd",
               "streetNo" : 321
            }
         ]
      },
      "custId" : "123"
   }
}
My question is, from address array, i want to select a particular document which  "city" : "bang", and  "streetNo" : 123 ,what is the query??

My query is :
db.customer.find({"customer.addresses.address":{"$elemMatch":{"city" : "bang", "streetNo" : 123}}})
and i got result,
{
   "customer" : {
      "addresses" : {
         "address" : [
            {
               "city" : "bang",
               "streetNo" : 123
            },
            {
               "city" : "hyd",
               "streetNo" : 321
            }
         ]
      },
      "custId" : "123"
   }
}

but my expected result is

{
   "customer" : {
      "addresses" : {
         "address" : [
            {
               "city" : "bang",
               "streetNo" : 123
            }
         ]
      },
      "custId" : "123"
   }
}




You didn't pass in any projection document.  That's the second document/argument passed to find.

You are selecting based on a single address, but read the two links I sent initially - you can specify exactly which element of the addresses.address array you want returned either with "$" (because you matched on it) or with $elemMatch (which you can use even if you selected on a different criteria than the address).


댓글 없음:

댓글 쓰기