开发者学堂课程【快速掌握 MongoDB 数据库:嵌套元素查询】学习笔记与课程紧密联系,让用户快速学习知识
课程地址:https://developer.aliyun.com/learning/course/400/detail/5201
嵌套元素查询
在 MongoDB 数据里面每一个集合数据可以继续保存其它的集合数据,例如有些学生需要保存家长信息:
db.students.insert ( { "name"
:"高大拿–A", "sex":"男", "age" :19, "score":89,"addr
ess
"course" :["语文","数学","英语","音乐","政治"]
"parents": [
{ "name" :"高大拿- A(父亲)" , "age" : 50"job":"工人""}})
{ "name" :"高大拿- A(母亲)" , "age" : 46"job":"职员""}})
db.students.insert({ "name"∵:
"高大拿–B","sex":"男
" ,"age":19,"score":89,"addr
ess
"course":["语文","数学",
"parents" : [
{"name": "高大拿-B(父亲)", "age" : 50 , "job":"处长""},
{ "name": "高大拿-B(母亲)", "age" : 46 , "job":"局长""}})
db.students.insert( {"name"
∵"高大拿- C""sex"."男","age ":19,"score":89,"address"
"course":["语文","数学","英语"],“
"parents": [
i "name": "高大拿-C(父亲)", "age" : 50 , "job":"工人""},I
{ "name”: "高大拿-C(母亲)", "age" : 46 , "job":"局长"}})
此时给出的内容是嵌套的集合,而这种集合的数据的判断只能够通过“$elemMatch”完成。
范例:查询出父母有人是局长的信息。
db.students.find(-
{
"$and" :[
{"age" : {"$gte" : 19}},
{"parents" : {
"$elemMatch" : i"job"
:"局长"}。
}
}]}).pretty
()
;-
结果:
"_id": objectId("5594b504eecd74894d1a0001") ,
"name"
:“高大拿- c”,
"sex"”
:男“,
"age”
: 19,
"score"
: 89,
"address"
:“海淀区,
"course"": [
语文","数学,“英语"
],
parents" : [
(
""name"
: "高大拿- c 〔父亲),
"age"
: 50,
job”
:"工人“
}
,
{
"name"
: “高大拿-c(母亲)”,
"age”
: 46,
job"
:"局长“
}
由于这种查询的时候条件比较麻烦,所以如果可能,尽量别搞这么复杂的数据结构组成。