温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2020-08-11 11:01:11 来源:ITPUB博客 阅读:160 作者:stonebox1122 栏目:关系型数据库
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" : "局长"
                }
        ]
}
由于这种查询的时候条件比较麻烦,所以如果可能,尽量别搞这么复杂。
向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI