mongodb - 聚合嵌套对象 mongodb
问题描述
你能帮我用mongodb写一些聚合查询吗?
我有下一个数据结构。
[
{
id: 1,
shouldPay: true,
users: [
{
id: 100,
items: [{...}],
tags: ['a', 'b', 'c', 'd']
},
{
id: 100,
items: [{...}],
tags: ['b', 'c', 'd']
},
{
id: 100,
items: [{...}],
tags: ['c', 'd']
}
],
}
]
结果我想得到类似的东西:
[
{
id: 1,
shouldPay: true,
user: {
id: 100,
items: [{...}],
tags: ['a', 'b', 'c', 'd']
}
}
]
主要思想是选择在标签中具有“a”字母或字母列表['a','b']的特定用户。
解决方案
您可以使用以下聚合
在管道的开头使用$match
过滤掉不包含"a"
和"b"
在tags
数组中的文档。然后使用$filter
with$setIsSubset
过滤掉嵌套数组。
$arrayELemAt
从数组中返回指定的元素。
db.collection.aggregate([
{ "$match": { "users.tags": { "$in": ["a", "b"] }}},
{ "$project": {
"users": {
"$arrayElemAt": [
{ "$filter": {
"input": "$users",
"cond": { "$setIsSubset": [["a", "b"], "$$this.tags"] }
}},
0
]
}
}}
])
推荐阅读
- matlab - 查找矩阵的子矩阵组合的最有效方法 [matlab]
- jquery - 用于mailto链接的jquery编码字符串
- python - 检查是否存在具有特定值的行,如果不存在则创建
- php - Where are the templates for the default pages in Silverstripe 4?
- google-apps-script - Google Spreadsheet Apps Script: Dialog box from HTML Service not loading when embedded
- amazon-redshift - AWS Redshift - 无法将外部表合并到本地目录中
- php - 创建一个二维数组,该数组根据每个 dateTime 对象之间的时间间隔对一组 dateTime 对象进行分组
- mongodb - MongoDB $near 查询准确性问题
- android - 隐式意图不适用于 Android Lyft 应用
- wordpress - 我的网站标识栏太大了。当我向下滚动时它也是静止的 - 我不想要那样。我该如何改变它?