Elyas74
Elyas74

Reputation: 548

view of query in mongodb

I have a collection ,this is one of it's docs :

{
"_id" : 1 ,
"first_name" : "john",
"phone" : [ 
    {
        "type" : "mobile",
        "number" : "9151112233"
    }, 
    {
        "type" : "home",
        "city_code" : 51,
        "number" : "55251544"
    }, 
    {
        "type" : "mobile",
        "number" : "9152425125"
    }
  ]
}

I'm searching for "phones" that contain type "mobile" and show them.

I need something like this :

{
 "number" : "9151112233",
 "number" : "9152425125"
}

I write this query for that :

db.main.find({ _id : 1 , 'phone.type' : "mobile" },{'phone.number' : true , _id : false}).forEach(printjson)

I want to show only numbers that their types are mobile but this query show all to numbers because this single doc contain others too. How can I fix it?

Upvotes: 0

Views: 71

Answers (1)

John Petrone
John Petrone

Reputation: 27517

I'd use the aggregation framework along with the $unwind, $match and $project commands. This:

db.main.aggregate({$unwind:"$phone"},{$match:{"phone.type":"mobile"}},{$project:{"phone.number":1,"_id":0}})

produces this output:

{ "phone" : { "number" : "9151112233" } }
{ "phone" : { "number" : "9152425125" } }

which only matches the mobile numbers.

http://docs.mongodb.org/manual/aggregation/

Upvotes: 1

Related Questions