How to print nested value who's field value is number

Hi all, I am trying to access nested value which is stored in number field like [0] ,[1]
please find the document below

{
    "_id" : ObjectId("5ee7ba7ea3ac0c3192c19e58"),
    "channel" : [ 
        {
            { 0 : [ {"name":"shubham"},{"phone": " 839393"] },
            { 1 : [ {"name":"Anant"},{"phone": " 839393"] }
       } ]
}

I want to find channel.0.name and channel.1.name using curser, But as field value is [0] and [1] I am not able to access the data.Please let me know if any altenative for this. I am using below query…

var cursor = db.getCollection('user_name').find({ })
while (cursor.hasNext()) {
var record = cursor.next();
print(record._id + ',' + record.channel.0.name + ',' + record.channel.1.name )}

If you need to access that data with print(), you can do it like this:

print(record._id + ‘,’ + record.channel[0].name + ‘,’ + record.channel[1].name )}

If you you want to query by that object properties, do this:

db.your_collection.find({ 'channel.0.name': 'Bill' });

Hi Slava,
Thank you .I want to use print the data and your method worked,But it is not printing for all conditions when there are many documents in which some field doesnt contain any data present(undefined).

{
“_id” : ObjectId(“5ee7ba7ea3ac0c3192c19e58”),
“channel” : [
{
{ 0 : [ {“name”:“shubham”},{“phone”: " 839393"] },
{ 1 : [ {“name”:“Anant”},{“phone”: " 839393"] }
} ],

{
“_id” : ObjectId(“5ee7ba7ea3ac0c3192c19e60”),
“channel” : [
{
{ 1 : [ {“name”:“Mauank”},{“phone”: " 839393"] }
} ]
}
}

In above for second document I am not having channel[0] but having channel[1].
I want output should be:
ObjectId Name Name
5ee7ba7ea3ac0c3192c19e58. shubham Anant
5ee7ba7ea3ac0c3192c19e60. undefined Mayank.

But while printing the data I am getting error as TypeError:record.channel[0] is undefined…
Please let me now if any solution for this…

Many Thanks in advance…

Try this:

let name0 = record.channel[0] ? record.channel[0].name : null;
let name1 = record.channel[1] ? record.channel[1].name : null;
print(`${record._id}, ${name0}, ${name2}`)};

This worked!! Thanks a lot Slava for your prompt responce.

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.