mongodb - 如何在 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 但无法成功。有人可以指导我如何做到这一点。
解决方案
因为{ $push: ["$location", "$status"] }
会给你错误The $push accumulator is a unary operator
。您必须通过将输出所需数组的单个对象传递给它来解决它。一种方法是:
[
{
"$match": {
"type": {
"$eq": "physical store"
}
}
},
{
"$group": {
"_id": null,
"stores": {
"$push": {
"$slice": [["$location", "$status"], 2]
}
}
}
}
]
推荐阅读
- r - 在 R foreach() 下并行运行时无法识别动态库依赖项
- spring - 可以在没有 springboot 的情况下使用“feign clients”吗?
- angular - Angular 使用 @HostListener 来监听按钮的特定点击
- python - 如何检查 numpy.array 是否存在?numpy数组的真值测试值?
- d3.js - 我的 d3 折线图看起来很奇怪,我不知道出了什么问题
- sql-server - 在 T-SQL 中组合具有重叠日期的行
- python - 没有线程的 Python 任务调度程序
- arrays - 将对象的索引获取到映射数组 React JS
- c# - 为什么没有实现接口:列表
是 ICollection - javascript - 如何添加两个以上的条件?例如: if , if , else