M Omayr
M Omayr

Reputation: 1351

Mongodb: how to perform subqueries?

I have documents which further have arrays. I want to query an array returned as a result of a previous query. For example I have

{
{_id : 001,
 data: [{
        value: 1,
        name: 'Roger'
       },
       {value: 2,
        name: 'Albert'
       },
       {value: 3,
        name: 'Allen'
       }]
},
{_id: 002,
data: [{value: 4,
        name: 'Allison'
       },
       {value: 5,
        name: 'Tom'
       }]
}
}

I can get document where _id is equal to 001 but I want to query it's data field where value is equal to 2 and 3. I don't know what is the solution for that. In SQL It could be performed with Sub-queries but I don't know how to do it in mongodb.

Upvotes: 2

Views: 6107

Answers (2)

Aseem Jain
Aseem Jain

Reputation: 351

Inserted 2 records in 2 different collections for join :

> db.employee.insert({eid:1,name:"premaseem"})
WriteResult({ "nInserted" : 1 })
> db.salary.insert({ eid:1, salary:6000 })
WriteResult({ "nInserted" : 1 })

Validated data in 2 tables :

> db.salary.find({ eid:1})
{ "_id" : ObjectId("56da1a5b2253b2199c53025b"), "eid" : 1, "salary" : 6000 }
> db.salary.find({ eid: db.employee.find({eid:1})  })
> db.employee.find({name : "prem" })
{ "_id" : ObjectId("56da19d42253b2199c53025a"), "eid" : 1, "name" : "prem" }

simulated join to get salary for employee premaseem :

> db.employee.find({name : "premaseem" }).map(function(d){  var obj =  db.salary.findOne({eid : d.eid  }); print(obj.salary)  }  )
6000

Upvotes: 0

Mark_H
Mark_H

Reputation: 790

Maybe you should use $elemMatch: http://docs.mongodb.org/manual/reference/operator/query/elemMatch/

a good example: http://docs.mongodb.org/manual/reference/operator/query/all/

1.db.test.save({d: [{k1:1, v1:1}]}) 
2.db.test.save({d: [{k1:1, v1:1}]}) 
3.db.test.find({d:{$elemMatch:{k1:1}}}) 

return:

{ "_id" : ObjectId("52aea61c54125a39453c8836"), "d" : [ { "k1" : 1, "v1" : 1 } ] }
{ "_id" : ObjectId("52aea62054125a39453c8837"), "d" : [ { "k1" : 1, "v1" : 1 } ] }

Note that $elemMatch query is different from $elemMatch projection.

Upvotes: 2

Related Questions