gpt4 book ai didi

database - 计算符合条件的数组元素

转载 作者:可可西里 更新时间:2023-11-01 09:12:43 25 4
gpt4 key购买 nike

我有一个名为“ session ”的 mongoDB 集合,参与者如下:

[
{
"_id" : 5b894357a0c84d5a5d221f25,
"conferenceName" : "myFirstConference",
"startDate" : 1535722327,
"endDate" : 1535722420,
"participants" : [
{
"name" : "user1",
"origin" : "internal",
"ip" : "192.168.0.2"
},
{
"name" : "user2",
"origin" : "external",
"ip" : "172.20.0.3"
},
]
},
...
]

我想得到以下结果:

[
{
"conferenceName" : "myFirstConference",
"startDate" : 1535722327,
"endDate" : 1535722420,
"internalUsersCount" : 1
"externalUsersCount" : 1,
},
...
]

我尝试了下面的请求,但它不起作用:

db.getCollection("conference").aggregate([
{
$addFields: {
internalUsersCount : {
$size : { "$participants" : {$elemMatch : { origin : "internal" }}}
},
externalUsersCount : {
$size : { "$participants" : {$elemMatch : { origin : "external" }}}
}
}
}
])

如何计算匹配 {"origin": "internal"}{"origin": "external"} 的“participant”数组元素?

最佳答案

您需要使用 $filter聚合以过滤掉 external 来源和 internal 来源以及 $size聚合来计算数组的长度。

像这样

db.collection.aggregate([
{ "$addFields": {
"internalUsersCount": {
"$size": {
"$filter": {
"input": "$participants",
"as": "part",
"cond": { "$eq": ["$$part.origin", "internal"]}
}
}
},
"externalUsersCount": {
"$size": {
"$filter": {
"input": "$participants",
"as": "part",
"cond": { "$eq": ["$$part.origin", "external"] }
}
}
}
}}
])

输出

[
{
"conferenceName": "myFirstConference",
"endDate": 1535722420,
"externalUsersCount": 1,
"internalUsersCount": 1,
"startDate": 1535722327
}
]

关于database - 计算符合条件的数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52167692/

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