使用 MongoDB 压缩两个数组并在重塑后创建新的对象数组
为此,请使用聚合以及 $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 } ] }
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP