ITPub博客

首页 > 数据库 > NoSQL > MongoDB之数据查询(嵌套集合)

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

原创 NoSQL 作者:stonebox1122 时间:2017-08-29 18:39:36 0 删除 编辑
在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" : "局长"
                }
        ]
}
由于这种查询的时候条件比较麻烦,所以如果可能,尽量别搞这么复杂。

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/28536251/viewspace-2144297/,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2013-12-13

  • 博文量
    204
  • 访问量
    1083246