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 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值