快上网专注成都网站设计 成都网站制作 成都网站建设
成都网站建设公司服务热线:028-86922220

网站建设知识

十年网站开发经验 + 多家企业客户 + 靠谱的建站团队

量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决

MongoDB之数据查询(嵌套集合)

在MongoDB数据库里面每一个集合数据可以继续保存其他的集合数据,例如有些人员保存家庭信息。

范例:增加数据
db.emp.insert({"name":"林A","sex":"男","age":22,"sal":8000,"loc":"北京","course":["语文","数学","英语","音乐","政治"],"parents":[{"name":"林A父亲","age":50,"job":"农民"},{"name":"林A母亲","age":49,"job":"工人"}]});
db.emp.insert({"name":"林B","sex":"男","age":30,"sal":8000,"loc":"北京","course":["语文","数学"],"parents":[{"name":"林B父亲","age":55,"job":"工人"},{"name":"林B母亲","age":52,"job":"农民"}]});
db.emp.insert({"name":"林C","sex":"男","age":35,"sal":8000,"loc":"北京","course":["语文","数学","英语"],"parents":[{"name":"林C父亲","age":60,"job":"工人"},{"name":"林C母亲","age":59,"job":"职员"}]});
db.emp.insert({"name":"林D","sex":"男","age":28,"sal":8000,"loc":"北京","course":["语文","数学","政治"],"parents":[{"name":"林D父亲","age":58,"job":"局长"},{"name":"林D母亲","age":54,"job":"处长"}]});
db.emp.insert({"name":"林E","sex":"男","age":40,"sal":8000,"loc":"北京","course":["语文","政治"],"parents":[{"name":"林E父亲","age":70,"job":"工人"},{"name":"林E母亲","age":68,"job":"局长"}]});

此时的内容是嵌套的集合,而这种集合的数据的判断只能通过“$elemMatch”来完成。

范例:查询出父母之中有局长的信息
> db.emp.find({"$and":[{"age":{"$gte":30}},{"parents":{"$elemMatch":{"job":"局长"}}}]}).pretty();
{
        "_id" : ObjectId("599148bf0184ff511bf02b95"),
        "name" : "林E",
        "sex" : "男",
        "age" : 40,
        "sal" : 8000,
        "loc" : "北京",
        "course" : [
                "语文",
                "政治"
        ],
        "parents" : [
                {
                        "name" : "林E父亲",
                        "age" : 70,
                        "job" : "工人"
                },
                {
                        "name" : "林E母亲",
                        "age" : 68,
                        "job" : "局长"
                }
        ]
}
由于这种查询的时候条件比较麻烦,所以如果可能,尽量别搞这么复杂。
新闻名称:MongoDB之数据查询(嵌套集合)
本文路径:http://6mz.cn/article/ihdpgo.html

其他资讯