Mongo DB 4

157 阅读1分钟

数组的查询 {字段:查询关键字}

  • 只要数组字段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严格匹配数组[查询关键字],就会被筛选上
  • 严格匹配:内容和顺序都要一样
//["technical"]
> db.crew.find({skills: ["technical"]}).pretty()
//["technical", "management"]
> db.crew.find({skills: ["technical", "management"]}).pretty()

数组的查询 {字段:{$all: [查询关键字]}}

  • 只要数组字段skills匹配数组内容,就会被筛选上
  • 内容一样,顺序无所谓
> db.crew.find({skills: {$all: ["technical", "management"]}})

数组的查询{字段:{$size: 长度值}}

  • 筛选,给定数组长度,的document
> 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}}

  • 第N个
//slice,只取出数组中的第一个元素
> db.crew.find({}, {skills: {$slice: 1}})
//
> db.crew.find({}, {skills: {$slice: [1,1]}})

数组元素 的选择 {}, {字段:{$slice: [N, M]}}

  • 跳过前N个,选择接下来的M个
//跳过1个,选择1个
> db.crew.find({}, {skills: {$slice: [1,1]}})

数组元素 的选择 {查询条件}, {字段.$: N}

  • 满足查询条件的元素开始,的前N个元素
//找到management开始后的1个元素
> 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") }