MongoDB 查询以解开两个数组
解开,表示从输入文档解构一个数组字段,为每个元素输出一个文档。
若要解开数组,请在 MongoDB 聚合中使用 $unwind。我们首先使用文档创建集合 −
> db.demo387.insertOne(
... {
...
... "Name" : "101",
... "Details1" : [
... {Value:100, Value1:50, Value2:40},
... {Value:200},
... {Value:300}
... ],
... "Details" : [
... {Value:100, Value1:30, Value2:26},
... {Value:200},
... {Value:300}
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e5d197022064be7ab44e7f8")
}借助 find() 方法显示集合中的所有文档 −
> db.demo387.find().pretty();
这将产生以下输出 −
{
"_id" : ObjectId("5e5d197022064be7ab44e7f8"),
"Name" : "101",
"Details1" : [
{
"Value" : 100,
"Value1" : 50,
"Value2" : 40
},
{
"Value" : 200
},
{
"Value" : 300
}
],
"Details" : [
{
"Value" : 100,
"Value1" : 30,
"Value2" : 26
},
{
"Value" : 200
},
{
"Value" : 300
}
]
}以下是聚合包含多个数组的文档的查询 −
> db.demo387.aggregate([
... { "$unwind": "$Details1" },
... { "$unwind": "$Details" },
... { "$match": { "$expr":
... { "$eq": ["$Details1.Value", "$Details.Value"] }
... }}
... ])这将产生以下输出 −
{ "_id" : ObjectId("5e5d197022064be7ab44e7f8"), "Name" : "101", "Details1" : { "Value" : 100, "Value1" : 50, "Value2" : 40 }, "Details" : { "Value" : 100, "Value1" : 30, "Value2" : 26 } }
{ "_id" : ObjectId("5e5d197022064be7ab44e7f8"), "Name" : "101", "Details1" : { "Value" : 200 }, "Details" : { "Value" : 200 } }
{ "_id" : ObjectId("5e5d197022064be7ab44e7f8"), "Name" : "101", "Details1" : { "Value" : 300 }, "Details" : { "Value" : 300 } }
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP