gpt4 book ai didi

mongodb - 从文档中的内部数组获取值的总出现次数

转载 作者:行者123 更新时间:2023-12-02 00:44:00 26 4
gpt4 key购买 nike

我的 MongoDB 文档是这样的

{  
"_id":"sdf23sddfsd",
"the_list":[
{
"Sentiment":[
"Negative",
"Positive",
"Positive"
]
},
{
"Sentiment":[
"Neutral",
"Positive"
]
}
],
"some_other_list":[
{
"Sentiment":[
"Positive",
"Positive",
"Positive"
]
}
]
}

我需要知道“the_list”字段中“Positive”的总出现次数,在上述情况下为 3,即“Positive”出现了 3 次。

显然,我从中得到一个文档数

db.tmp.find({ "the_list.Sentiment": { "$in": ["Positive"] } }).count()

还有一个来自:

db.tmp.aggregate(
{ $match: { "the_list.Sentiment": { "$in": ["Positive"] } } }
, { $group: { _id: "_id", count: { $sum: 1 } } }
)

最后,下面我在试验,还是得到零

db.tmp.aggregate(
{
$group: {
_id: "_id", count: {
$sum: {
$cond: [{"$in": ["Positive","$the_list.Sentiment"]} , 1, 0]
}
}
}
}
)

最佳答案

您需要过滤子文档数组以返回等于“Positive”的元素,并使用 $map 和“the_list”数组中的每个子文档返回结果数组的总和或等于“Positive”的元素数$filter 。从那里,您需要做的就是使用 $reduce 运算符合并总和

[
{
"$project": {
"count": {
"$reduce": {
"input": {
"$map": {
"input": "$the_list",
"in": {
"$filter": {
"input": "$$this.Sentiment",
"cond": {
"$eq": [
"$$this",
"Positive"
]
}
}
}
}
},
"initialValue": 0,
"in": {
"$add": [
"$$value",
{
"$size": "$$this"
}
]
}
}
}
}
}
]

在 MongoDB 3.4 之前,您需要一种不同的方法,如此管道所示

[
{
"$project": {
"arrayOfSum": {
"$sum": {
"$map": {
"input": "$the_list",
"in": {
"$size": {
"$filter": {
"input": "$$this.Sentiment",
"cond": {
"$eq": [
"$$this",
"Positive"
]
}
}
}
}
}
}
}
}
}
]

关于mongodb - 从文档中的内部数组获取值的总出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45021458/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com