MongoDB的。在Subdocument中查询数组

时间:2013-10-01 18:29:18

标签: javascript arrays mongodb

我是mongodb的新手,所以如果我使用了错误的条款,请纠正我:

我有以下文件(摘录)

{
    "_id" : ObjectId("524b0a1a7294ec8a39d4230f"),
    "name" : "Irbesartan",
    "decompositions" : [
            "IRB_444",
            "IRB_442",
            "IRB_446",
            "Valsartan acid"
    ],
    "precursor" : [
            {
                    "mass" : 429,
                    "ion" : "+H",
                    "charge" : "+",
                    "fragments" : [
                            207,
                            195,
                            180
                    ]
            },
            {
                    "mass" : 427.2252,
                    "ion" : "-H",
                    "charge" : "-",
                    "fragments" : [
                            193,
                            399
                    ]
            }
    ]
}

db.substances.findOne({name: "Irbesartan"}).precursor

我得到以下

[
    {
            "mass" : 429,
            "ion" : "+H",
            "charge" : "+",
            "fragments" : [
                    207,
                    195,
                    180
            ]
    },
    {
            "mass" : 427.2252,
            "ion" : "-H",
            "charge" : "-",
            "fragments" : [
                    193,
                    399
            ]
    }
]

但我想访问里面的字段,特别是片段数组(使用Mongo Shell)

这可以在一个查询中使用吗?

或者将前体存储为数组而不是子文档更好吗?

1 个答案:

答案 0 :(得分:1)

例如查询

db.substances.distinct("precursor.fragments", {name: "Irbesartan"})

给出:

[ 180, 193, 195, 207, 399 ]

db.substances.findOne({name: "Irbesartan"}).precursor.map(function(r) {
  return r.fragments;
})

给出

[ [ 207, 195, 180 ], [ 193, 399 ] ]