0

I am working on project on which I had to make recommendation system for users in website.I am new to Mongodb. I want to retrieve the names/id of users who have "frnds.type"=1 in below code.

{
"_id" : ObjectId("56a9fcc15b4e12369150d6ef"),
"name" : "Udit",
"venue" : {
    "state" : "Rajasthan",
    "city" : "Jaipur",
    "ll" : [
        "26.9000",
        "75.8000"
    ]
},
"lsv" : [
    0.14,
    0.18,
    0.24,
    0.17,
    0.05,
    0.17,
    0.05
],
"username" : "udit",
"frnds" : [
    {
        "id" : "amit",
        "type" : 1
    },
    {
        "id" : "nakul",
        "type" : 0
    },
    {
        "id" : "verma",
        "type" : 1
    }
]

}

I have written one query but it is giving wrong results

db.users.find({"username":"udit"},{"frnds":{"$elemMatch":{"type":1}}}).pretty()

I want result in this manner :

[ { "id":"amit", "type":1 }, { "id":"verma", "type":1 } ]

Udit Kumawat
  • 654
  • 1
  • 8
  • 21
  • please have a check to :http://stackoverflow.com/questions/21113543/mongodb-get-subdocument – Louis F. Jan 28 '16 at 13:07
  • that is possible in mongoDB version 3.2 only – undefined_variable Jan 28 '16 at 13:23
  • Possible duplicate of [Retrieve only the queried element in an object array in MongoDB collection](http://stackoverflow.com/questions/3985214/retrieve-only-the-queried-element-in-an-object-array-in-mongodb-collection) – styvane Jan 28 '16 at 14:02

1 Answers1

1

Try with Aggregation Framework as below.

 db.users.aggregate([{
    $match: {username: 'udit'}, 
    {$unwind: '$frnds'}, 
    {$match: {'frnds.type': 1}}, 
    {$group: {frnds: {$push: "$frnds"}}
 }]);
zangw
  • 43,869
  • 19
  • 177
  • 214