I have two main collections in my MongoDB, users & address. I am using '$ref' and '$id' in my 1st collection (users) to refer to documents of the 2nd collection (address). I want to write a query to show details of the user and his addresses.
This is my first collection 'users'. It has 1 document
{
"_id" : ObjectId("52ffc33cd85242f436000001"),
"contact" : "987654321",
"dob" : "01-01-1991",
"name" : "Tom Benzamin",
"address" : [
{
"$ref" : "address",
"$id" : ObjectId("534009e4d852427820000002"),
"$db" : "test"
},
{
"$ref" : "address",
"$id" : ObjectId("52ffc4a5d85242602e000000"),
"$db" : "test"
}
]
}
This is my 2nd collection 'address'. It has 3 documents
{
"_id" : ObjectId("52ffc4a5d85242602e000000"),
"building" : "22 A, Indiana Apt",
"pincode" : 123456.0000000000000000,
"city" : "Los Angeles",
"state" : "California"
},
{
"_id" : ObjectId("52ffc4a5d85242602e000001"),
"building" : "170 A, Acropolis Apt",
"pincode" : 456789.0000000000000000,
"city" : "Chicago",
"state" : "Illinois"
},
{
"_id" : ObjectId("534009e4d852427820000002"),
"building" : "22 A, Indiana Apt",
"pincode" : 123456.0000000000000000,
"city" : "Los Angeles",
"state" : "California"
}
I have write this code but it is not working. It show the word 'null' when I run it
var user = db.users.findOne({"name":"Tom Benzamin"})
var dbRef = user.address
db[dbRef.$ref].findOne({"_id":(dbRef.$id)})
It shows null because dbRef is an array:
{
"0" : {
"$ref" : "address",
"$id" : ObjectId("52ffc4a5d85242602e000000"),
"$db" : "test"
},
"1" : {
"$ref" : "address",
"$id" : ObjectId("534009e4d852427820000002"),
"$db" : "test"
}
}
Try with this:
var user = db.users.findOne({"name":"Tom Benzamin"})
var dbRef = user.address
var ids = new Array();
for (i = 0; i < dbRef.length; i++){
ids.push(dbRef[i].$id)
}
db[dbRef[0].$ref].find({"_id":{$in:ids}});