Mohamed Challouf
Mohamed Challouf

Reputation: 113

How can i retrieve a subrecord from mongo DB

I have a db that looks like this :

{
    "_id" : ObjectId("50525e55467f67da3f8baf06"),
    "client" : "client1" 
}
{
    "_id" : ObjectId("505262f0deed32a758410b1c"),
    "client" : "client2" 
}
{
    "_id" : ObjectId("5052fe0a37083fd981616589"),
    "client" : "client3",
    "products" : [
        {"name" : "product1"},
        {"name" : "product2"}
    ]
}

How can i retrieve the product list of client3 without retrieving the client3 record ? The output should look like this :

[
    {"name" : "product1"},
    {"name" : "product2"}
]

Upvotes: 0

Views: 248

Answers (2)

John Page
John Page

Reputation: 1

Also - if you want to get just the matching subrecord - see here

http://docs.mongodb.org/manual/reference/operator/projection/positional/

you use the $ operator in the project portion of find to specify the n'th subrecord where that is the first to match your query.

Upvotes: 0

theyetiman
theyetiman

Reputation: 8908

I don't think you can completely exclude the client3 record as the products are part of this record, but you can select just the products field like this:

db.<dbname>.find({ 'client' : 'client3' }, { 'products' : 1, '_id' : 0 })

Upvotes: 2

Related Questions