MongoDB 数组操作符与运算操作符

数组操作

创建包含数组和嵌套数组的文档

> db.accounts.insert({ name:"alice2", balance:100,contact:[13611111111,"Guangzhou"] })
WriteResult({ "nInserted" : 1 })
> db.accounts.insert({ name:"alice2", balance:100,contact:[[13611111111,13622222222],"Guangzhou"] })
WriteResult({ "nInserted" : 1 })

查询数组元素与嵌套数组

> db.accounts.find({contact:{$all:[13611111111]}})
{ "_id" : ObjectId("5d7f8f0da7b5867462dee50f"), "name" : "alice2", "balance" : 100, "contact" : [ 13611111111, "Guangzhou" ] }
> db.accounts.find({contact:{$all:[[13611111111]]}})
> db.accounts.find({contact:{$all:[[13611111111,13622222222]]}})
{ "_id" : ObjectId("5d7f8f21a7b5867462dee510"), "name" : "alice2", "balance" : 100, "contact" : [ [ 13611111111, 13622222222 ], "Guangzhou" ] }

筛选数组元素符合特定条件的记录

> db.accounts.find({contact:{$elemMatch:{$gt:10000000000}}})
{ "_id" : ObjectId("5d7f8f0da7b5867462dee50f"), "name" : "alice2", "balance" : 100, "contact" : [ 13611111111, "Guangzhou" ] }

regex 运算操作符

# i 选项,不区分大小写
> db.accounts.find({name:{$regex:/^A/,$options:'i'}})
{ "_id" : "account1", "name" : "alice2", "balance" : 100 }
{ "_id" : ObjectId("5d7f8f21a7b5867462dee510"), "name" : "alice2", "balance" : 100, "contact" : [ [ 13611111111, 13622222222 ], "Guangzhou" ] }

配合 $in 使用的时候,无需使用 $regex 关键字

> db.accounts.find({name:{$in:[/^A/i,/^D/i]}})
{ "_id" : "account1", "name" : "alice2", "balance" : 100 }
{ "_id" : ObjectId("5d7f25f4aecbd2bc0fa821b4"), "name" : "david", "balance" : 200 }

posted on 2020-04-05 22:33  思过崖灬  阅读(412)  评论(0编辑  收藏  举报

导航