Nalu
Nalu

Reputation: 195

How to print nested array using mongo query

I'm trying to print the values of an nested array.But getting execute script error.How do I print object BSON and avoid error in for nested array. Note : I want to do with print and not find().

Customer schema

 {
 "name" : "Sam",   
 "phone" : [ 
 {
   "home" : "123456",
  "work" : "045842"
 }]}

query

db.getCollection('customer').find({}).forEach( function(cust) 
{
print("Customer Name : " + cust.name); // prints Sam
print("Home Contact : " + cust.phone) // prints [object BSON]
print("Home Contact : " + cust.phone.home) // throws error
});

Upvotes: 0

Views: 1733

Answers (2)

gbackmania
gbackmania

Reputation: 890

You could use aggregation if there are multiple items in the array

 db.collectionName.aggregate([

    { $unwind: { path: "$phone", preserveNullAndEmptyArrays: true}},

 ]).forEach(function(doc){

    print(doc.name)
    if(doc.phone !== undefined) print(doc.phone.home)
    if(doc.phone !== undefined) print(doc.phone.work)
 })

Upvotes: 1

Nuno Sousa
Nuno Sousa

Reputation: 882

You just need to convert the object to string and access the array;

   print("Home Contact : " + JSON.stringify(cust.phone[0])) 
    // prints ` Home Contact: { "home" : "123456", "work" : "045842" }
   print("Home Contact : " + cust.phone[0].home) // "123456"

An example:

aireclaimRs:PRIMARY> use test
switched to db test
aireclaimRs:PRIMARY> db.createCollection('customer')
{ "ok" : 1 }
aireclaimRs:PRIMARY> db.customer.insert( {
...  "name" : "Sam",   
...  "phone" : [ 
...  {
...    "home" : "123456",
...   "work" : "045842"
...  }]})
WriteResult({ "nInserted" : 1 })
aireclaimRs:PRIMARY> db.getCollection('customer').find().forEach(function(cust){
... print("Customer Name : " + cust.name);
... print("Homes Contact : " + JSON.stringify(cust.phone[0]));
... print("Home Contact : " + cust.phone[0].home)
... })
Customer Name : Sam
Homes Contact : {"home":"123456","work":"045842"}
Home Contact : 123456

Upvotes: 1

Related Questions