数据准备:
db.doc_1.insertMany([
{
"test1":["a1","b1","c1"],
"test2":{"n1":"123","n2":"321"},
"test3":[1,2,3],
"name":"马国",
"age":31,
},
{
"test1":["a1","b2","c2"],
"test2":{"n1":"456","n2":"654"},
"test3":[1,3,3],
"name":"牛宝宝",
"age":34,
},
{
"test1":["a2","b3","c1"],
"test2":{"n1":"789","n2":"987"},
"test3":[1,1,3],
"name":"马宝宝",
"age":32,
},
{
"test1":["a2","b1","c3"],
"test2":{"n1":"132","n2":"312"},
"test3":[1,2,5],
"name":"马保国",
"age":29,
},
{
"test1":["a3","b2","c2"],
"test2":{"n1":"465","n2":"546"},
"test3":[1,5,3],
"name":"董三方",
"age":35,
},
{
"test1":["a4","b3","c3"],
"test2":{"n1":"798","n2":"978"},
"test3":[5,2,3],
"name":"马保",
"age":34,
}
])
目标:
掌握几个关键词:$group, $match, $unwind
1.通过聚合查询,过滤掉age重复的数据
db.doc_1.aggregate([
{
$group:{
_id:{
age:"$age"
},
age:{
"$last":"$age"
},
name:{
"$last":"$name"
}
}
}
])
结果:
2.通过聚合查询,查询:test1包含a1 && (test3>=3 && test3<=5)的数据
//方法1
db.doc_1.aggregate([
{
$match : {
'test1' : {$in : ['a1']},
'test3' : {$gte:3,$lte:5}
}
}
])
//方法2
db.doc_1.aggregate([
{
$match:{
test1:{
$elemMatch:{
$eq:"a1"
}
},
test3:{
$elemMatch:{$gte:3,$lte:5}
}
}
}
])
结果:
// 1
{
"_id": ObjectId("60c53f2e05c904135f531052"),
"test1": [
"a1",
"b1",
"c1"
],
"test2": {
"n1": "123",
"n2": "321"
},
"test3": [
1,
2,
3
],
"name": "马国",
"age": 31
}
// 2
{
"_id": ObjectId("60c53f2e05c904135f531053"),
"test1": [
"a1",
"b2",
"c2"
],
"test2": {
"n1": "456",
"n2": "654"
},
"test3": [
1,
3,
3
],
"name": "牛宝宝",
"age": 34
}
3.通过聚合查询将test1拆分为多条数据(提示:unwind)
db.test.aggregate([
{$unwind:"$test1"}
])
结果:
4.将前四个查询合并成一个,并贴出查询结果
db.doc_1.aggregate([
{
$group:{
_id:{"age":"$age"},
test1:{$last:"$test1"},
test2:{$last:"$test2"},
test3:{$last:"$test3"},
name:{$last:"$name"},
age:{$last:"$age"},
}
},
{
$match:{
test1:{
$elemMatch:{
$eq:"a1"
}
},
test3:{
$elemMatch:{$gte:3,$lte:5}
}
}
},
{$unwind:"$test1"}
])
查询结果:
// 1
{
"_id": {
"age": 31
},
"test1": "a1",
"test2": {
"n1": "123",
"n2": "321"
},
"test3": [
1,
2,
3
],
"name": "马国",
"age": 31
}
// 2
{
"_id": {
"age": 31
},
"test1": "b1",
"test2": {
"n1": "123",
"n2": "321"
},
"test3": [
1,
2,
3
],
"name": "马国",
"age": 31
}
// 3
{
"_id": {
"age": 31
},
"test1": "c1",
"test2": {
"n1": "123",
"n2": "321"
},
"test3": [
1,
2,
3
],
"name": "马国",
"age": 31
}