mongoDB管道--数组查询
1. 初始化数据
db.createCollection("t_demo")
db.t_demo.insertMany([
{num:[1,2,3], obj: [{name: "zhang1", age: 12}, {name: "li1", age: 13}]},
{num:[1,2], obj: [{name: "zhang2", age: 12}, {name: "li2", age: 13}]},
{num:[1,], obj: [{name: "zhang3", age: 14}, {name: "li2", age: 15}]},
])
2. 基本数据类型查询
in
数组中匹配到任意一个all
数组中要包含所有
1. 查询包含1或者2
db.t_demo.aggregate([{
$match: {
num: {$in: [1,2]}
}
}])
查出3条数据
/* 1 */
{
"_id" : ObjectId("6210a06d13adc55355d6495f"),
"num" : [1, 2, 3],
"obj" : [{
"name" : "zhang1",
"age" : 12
}, {
"name" : "li1",
"age" : 13
}]
}
/* 2 */
{
"_id" : ObjectId("6210a06d13adc55355d64960"),
"num" : [1, 2],
"obj" : [{
"name" : "zhang2",
"age" : 12
}, {
"name" : "li2",
"age" : 13
}]
}
/* 3 */
{
"_id" : ObjectId("6210a06d13adc55355d64961"),
"num" : [1],
"obj" : [{
"name" : "zhang3",
"age" : 14
}, {
"name" : "li2",
"age" : 15
}]
}
2. 查询包含1和2
db.t_demo.aggregate([{
$match: {
num: {$all: [1,2]}
}
}])
结果2条数据
/* 1 */
{
"_id" : ObjectId("6210a06d13adc55355d6495f"),
"num" : [1, 2, 3],
"obj" : [{
"name" : "zhang1",
"age" : 12
}, {
"name" : "li1",
"age" : 13
}]
}
/* 2 */
{
"_id" : ObjectId("6210a06d13adc55355d64960"),
"num" : [1, 2],
"obj" : [{
"name" : "zhang2",
"age" : 12
}, {
"name" : "li2",
"age" : 13
}]
}
3. 查询等于1和2
这里不使用
$eq
的原因是:$eq
要保证顺序也要一致[1,2]
和[2,1]
是不相等的
db.t_demo.aggregate([{
$match: {
num: {$all: [1,2]},
num: {$size: 2}
}
}])
结果1条
/* 1 */
{
"_id" : ObjectId("6210a06d13adc55355d64960"),
"num" : [1, 2],
"obj" : [{
"name" : "zhang2",
"age" : 12
}, {
"name" : "li2",
"age" : 13
}]
}
3. 对象类型查询
通过$elemMatch
或者数组名.属性名
进行查询
# $elemMatch
db.t_demo.aggregate([{
$match: {
obj: {$elemMatch: {age:12}}
}
}])
db.t_demo.aggregate([{
$match: {
obj: {$elemMatch: {name: "zhang1", age: 12}}
}
}])
# 数组.
db.t_demo.aggregate([{
$match: {
"obj.age": 12
}
}])
db.t_demo.aggregate([{
$match: {
"obj.name": "zhang1",
"obj.age": 12
}
}])