gpt4 book ai didi

mongodb - mongodb $match 中的多个条件

转载 作者:行者123 更新时间:2023-12-04 10:11:26 25 4
gpt4 key购买 nike

我有一个集合 AccountSupport。我有一系列支持属性。我想过滤父属性和数组属性的记录

db = {
"AccountSupport": [
{
"_id" : ObjectId("5e9c6170b38c373530c5b00a"),
"accountName" : "domestic",
"supports" : [
{
"subject" : "Traverse",
"desc" : "Travers support consolidation",
},
{
"subject" : "Non Traverse",
"desc" : "Non Travers support consolidation",
},
{
"subject" : "Domestic Traverse",
"desc" : "Domestic Travers support consolidation",
}
],

}

我想过滤 accountName 和 support.subject。

以下是我的查询
db.AccountSupport.aggregate([
{
"$match": {
"$and": [
{
"supports.subject": "Traverse"
},
{
"accountName": "domestic"
}
]
}
},
{
"$unwind": "$supports"
},
{
"$project": {
"SupportName": "$supports.subject",
"desc": "$supports.desc"
}
}
])

上面的查询返回特定 accountName 的所有支持,而我只想要匹配主题的单个对象。以上是最简单的方法吗?

MongoPlayGround

MongoPlayGround for my query

最佳答案

进行了一些实验,但试试这个:

db.AccountSupport.aggregate([
{
$match: {
"accountName": "domestic",
"supports.subject": "Traverse"
}
},
{
$project: {
accountName: "$accountName",
subject: {
$filter: {
input: "$supports",
as: "supports",
cond: {
$eq: [
"$$supports.subject",
"Traverse"
]
}
}
},
_id: 0
}
}
])

返回:
[
{
"accountName": "domestic",
"subject": [
{
"desc": "Travers support consolidation",
"subject": "Traverse"
}
]
}
]

关于mongodb - mongodb $match 中的多个条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61322309/

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