我有一个=>看板文档结构,=>columns=>cards.properties
我需要确定具有相同属性的卡片的数量(查看我的所有列),并将其记为我的卡片的一个名为"matchedCards“的新属性
例如,我有这样一个看板:

这里我有3个椰子,1个苹果树和2个苹果。
我将把我的Demo Playground留在这里:
我在每张卡片上都尝试了类似“matchedElements”:{‘$sum’:“$$this.title”}这样的东西,但我不知道怎么做。
我的最终结果应该如下所示:

发布于 2021-07-11 07:14:33
您还应该使用db.collection.count()在数据请求中传递查询
发布于 2021-07-11 14:30:35
您可能会得到以下结果:
{
"_id" : "Apple",
"count" : 2
},
{
"_id" : "Coconut",
"count" : 3
},
{
"_id" : "Pinapple",
"count" : 1
}通过发出以下查询:
db.collection.aggregate([
{
"$match": {
"_id": ObjectId("60ea230502e5ce273cf6e350")
}
},
{
$project: {
_id: 0,
_titles: {
$reduce: {
input: "$columns.cards.title",
initialValue: [],
in: { $concatArrays: ["$$value", "$$this"] }
}
}
}
},
{
$unwind: "$_titles"
},
{
$group: {
_id: "$_titles",
count: {
$sum: 1
}
}
}
])但是您将发出第二个db查询,并将匹配卡片标题并设置客户端的计数。
您可以像这样使用$facet来避免第二个查询:https://mongoplayground.net/p/69XHSaZbHGK
这是我能想到的最好的办法了。也许其他人会有更好/更有效的方法。
发布于 2021-07-11 14:48:33
您可以在聚合管道中多次使用$unwind来获得所需的结果。
db.collection.aggregate([
{
"$match": {
"_id": ObjectId("60ea230502e5ce273cf6e350")
}
},
{
$unwind: "$columns"
},
{
$unwind: "$columns.cards"
},
{
$group: {
_id: "$columns.cards.title",
"count": {
"$sum": 1
}
}
}
])此解决方案适用于两个嵌套数组中的任意数量的元素,但请注意,$unwind会创建子文档的副本,这将对性能进行权衡。
https://stackoverflow.com/questions/68332137
复制相似问题