为此,将aggregate和$zip一起使用。zip用于转置数组。让我们创建一个包含文档的集合-
> db.demo339.insertOne({Id:101,Score1:["98","56"],Score2:[67,89]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e529ee5f8647eb59e5620a2")
}在find()方法的帮助下显示集合中的所有文档-
> db.demo339.find();
这将产生以下输出-
{ "_id" : ObjectId("5e529ee5f8647eb59e5620a2"), "Id" : 101, "Score1" : [ "98", "56" ], "Score2" : [ 67, 89 ] }以下是使用$zip压缩两个数组并创建一个新的对象数组的查询-
> db.demo339.aggregate([
... {
... "$project": {
... "AllArrayObject": {
... "$map": {
... "input": {
... "$objectToArray": {
... "$arrayToObject": {
... "$zip": {
... "inputs": [
... "$Score1",
... "$Score2"
... ]
... }
... }
... }
... },
.
... "as": "el",
... "in": {
... "Score1": "$$el.k",
... "Score2": "$$el.v"
... }
... }
... }
... }
... }
... ])这将产生以下输出-
{ "_id" : ObjectId("5e529ee5f8647eb59e5620a2"), "AllArrayObject" : [ { "Score1" : "98", "Score2" : 67 }, { "Score1" : "56", "Score2" : 89 } ] }