遍历mongoDB中的非关联数组 [英] To loop through non associative array in mongoDB

查看:50
本文介绍了遍历mongoDB中的非关联数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文档集合,该文档包含嵌套数组形式的数据以及具有不同格式的数组列表.

I have a collection with a document having data in nested array form with array list of different format.

输入:

{ 
    "_id" : ObjectId("5262d2eaca24d995f4958083"),
    "array" : [
        {
            "name" : "sam",
            "roll" : 21 
        },  
        {
            "name" : "vam",
            "roll" : 22
        },  
        {
            "name" : "mam",
            "roll" : 23
        },  
        {
            "name" : "jam",
            "roll" : [31, 32, 33, 34]
        },
        {
            "name" : [
                {"name" : "lam" },
                {"name" : "ham" },
                {"name" : "pam" }
            ],
            "roll" :[
                {"roll" : 41},
                {"roll" : 42},
                {"roll" : 43}
            ]
        }
    ]
}

(在上面的代码中,array [4]与先前的数组相比具有不同的格式)

(In the above code the array[4] has different format compared to its predecessors)

我想获取array [4]的所有名称,即lam,ham,pam

I want to get all the names of array[4] i.e lam,ham,pam

所需的输出:

lam
火腿
pam

lam
ham
pam

我的方法:我尝试了以下代码

My Approach: I tried the following code

db.test1.find().forEach(function(x)
{
    x.array.forEach(function(y)
    {
        y.name.forEach(function(z)
        {
            print(z.name);
        })
    })
})

但这给出了错误原因:

错误:Sam没有方法'forEach':

error: Sam has no method 'forEach' :

因为它试图遍历名称(数组列表1),但是由于它只有一个数据,即"sam",因此forEach对此不起作用,导致forEach仅对关联数组有效.

because it tries to loop through name (arraylist 1) but since it has only one data i.e 'sam', forEach doesn't work for this, cause forEach only works for associative Array's.

仅供参考:当我为嵌套数组尝试相同的代码,且其所有列表的数组格式均相同时,我可以获得所需的输出.

FYI: When I tried the same code for nested array with array format being the same for all its list, I could get the desired output.

请帮助我使用mongo shell正确获取代码.

Please help me get the code right using mongo shell.

先感谢:)

推荐答案

您需要检查y.name是否为数组,然后才尝试打印值.这样的事情应该起作用:

You need to check if y.name is an array and only then try to print the values. Something like this should work:

db.test1.find().forEach(function (x) {
    x.array.forEach(function (y) {
        if (y.name instanceof Array) {
            y.name.forEach(function (z) {
                print(z.name);
            });
        }
    });
});

这篇关于遍历mongoDB中的非关联数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆