数组的查询 {字段:查询关键字}
- 只要数组字段skills包含
查询关键字值technical,就会被筛选上
> db.crew.find({skills: "technical"}).pretty()
{
"_id" : ObjectId("619380fe204711818273f99c"),
"name" : "Andrei Luca",
"skills" : [
"technical",
"management"
],
"address" : {
"city" : "Bucharest",
"country" : "Romania"
}
}
{
"_id" : ObjectId("619380fe204711818273f99d"),
"name" : "Anna Smith",
"skills" : [
"technical",
"management"
],
"address" : {
"city" : "Bucharest",
"country" : "Romania"
}
}
数组的查询{字段:[查询关键字]}
- 只要数组字段skills严格匹配数组
[查询关键字],就会被筛选上
- 严格匹配:内容和顺序都要一样
> db.crew.find({skills: ["technical"]}).pretty()
> db.crew.find({skills: ["technical", "management"]}).pretty()
数组的查询 {字段:{$all: [查询关键字]}}
- 只要数组字段skills匹配数组内容,就会被筛选上
- 内容一样,顺序无所谓
> db.crew.find({skills: {$all: ["technical", "management"]}})
数组的查询{字段:{$size: 长度值}}
> db.crew.find({skills: {$size:2}})
> db.crew.find({skills: {$size:0}})
数组的查询 {字段:{$elemMatch: 查询条件}}
> db.crew.find({skills: {$elemMatch: {name: "flying", lvl: {$gt: 7}}}})
数组元素 的选择 {}, {字段:{$slice: N}}
> db.crew.find({}, {skills: {$slice: 1}})
> db.crew.find({}, {skills: {$slice: [1,1]}})
数组元素 的选择 {}, {字段:{$slice: [N, M]}}
> db.crew.find({}, {skills: {$slice: [1,1]}})
数组元素 的选择 {查询条件}, {字段.$: N}
> db.crew.find({skills: "management"}, {"skills.$": 1})
数组元素 的选择 {}, {字段: {$elemMatch: 查询条件}}
> db.crew.find({}, {skills: {$elemMatch: {lvl: {$gt: 7}}}})
{ "_id" : ObjectId("619380fe204711818273f99b") }
{ "_id" : ObjectId("619380fe204711818273f99c") }
{ "_id" : ObjectId("619380fe204711818273f99d") }
{ "_id" : ObjectId("619380fe204711818273f99e") }