如何在mongodb中获得多维数组数据?

时间:2015-09-07 06:36:41

标签: mongodb aggregation-framework

我想从以下输出中获取所有'用户名':

> doc=db.instagram1.findOne();
{
        "_id" : ObjectId("55bfba2bc24e980ec46f59c2"),
        "meta" : {
                "code" : NumberLong(200)
        },
        "data" : [
                {
                        "username" : "lifteds0ul",
                        "profile_picture" : "https://igcdn-photos-b-a.akamaihd.net/hphotos-ak-xfa1/t51.2885-19/s150x150/11249117_1590613231201553_906635879_a.jpg",
                        "id" : "2139603325",
                        "full_name" : "River Sage"
                },
                {
                        "username" : "noony__alhosawy",
                        "profile_picture" : "https://igcdn-photos-a-a.akamaihd.net/hphotos-ak-xaf1/t51.2885-19/s150x150/11326999_1464806933841520_1635942624_a.jpg",
                        "id" : "2092127241",
                        "full_name" : "NEAMA"
                },
                {
                        "username" : "_perverse",
                        "profile_picture" : "https://igcdn-photos-g-a.akamaihd.net/hphotos-ak-xaf1/t51.2885-19/s150x150/11312547_878996775481318_911042248_a.jpg",
                        "id" : "2090297101",
                        "full_name" : ""
                },
etc....

它在数据值

之内

我的尝试:

> for (data in doc) print(username);
data
data
data
> for (username in doc) print(username);
_id
meta
data
> for (data[username] in doc) print(username);
data
data
data
> for (data:[username] in doc) print(username);
2015-09-06T06:57:34.148+0000 SyntaxError: Unexpected token :

预期产出:

lifteds0ul
noony__alhosawy
_perverse
...

作为第二个警告,如果我可以将'用户名'计为第二个单独的查询,那将非常有用。

1 个答案:

答案 0 :(得分:2)

您需要的只是"aggregation"和两个预测。在第一个$project阶段,您使用$map运算符,该运算符返回"用户名"的数组。和;在第二个你需要使用$size运算符来计算"用户名"在你的阵列中。

{
        "usernames" : [
                "lifteds0ul",
                "noony__alhosawy",
                "_perverse"
        ],
        "count" : 3
}

返回:

def self.not_returned
  where.not(Return.where("returns.sale_id = sales.id").exists)
end