首页 > 解决方案 > 如何在 MongoDB 上创建包含数组的数组

问题描述

我正在尝试对 mongodb 进行查询。我想获得一个包含每个文档的 [location, status] 的数组。这就是我的收藏的样子

{
"_id": 1,
  "status": "OPEN",
  "location": "Costa Rica",
  "type": "virtual store"
},
{
  "_id": 2,
  "status": "CLOSED",
  "location": "El Salvador"
  "type": "virtual store"
},
{
  "_id": 3,
  "status": "OPEN",
  "location": "Mexico",
  "type": "physical store"
},
{
  "_id": 4,
  "status": "CLOSED",
  "location": "Nicaragua",
"type": "physical store"
}

我使用聚合框架进行了查询,试图获取与该特定商店类型匹配的所有文档。

{
 {'$match': {
   'type': { '$eq': "physical store"}
 }
}

我想要的是这样的:

{
  {
  'stores': [
    ["Mexico", "OPEN"],
    ["Nicaragua", "CLOSED"]
   ]
 },
}

我尝试使用 $push 但无法成功。有人可以指导我如何做到这一点。

标签: mongodbnosql-aggregation

解决方案


因为{ $push: ["$location", "$status"] }会给你错误The $push accumulator is a unary operator。您必须通过将输出所需数组的单个对象传递给它来解决它。一种方法是:

[
  {
    "$match": {
      "type": {
        "$eq": "physical store"
      }
    }
  },
  {
    "$group": {
      "_id": null,
      "stores": {
        "$push": {
          "$slice": [["$location", "$status"], 2]
        }
      }
    }
  }
]

推荐阅读