gpt4 book ai didi

c# - MongoDB C# 驱动程序 - $ 与相同字段匹配两次

转载 作者:太空宇宙 更新时间:2023-11-03 10:41:59 25 4
gpt4 key购买 nike

假设我有一组如下所示的调查响应文档:

{
_id: ...
surveryId: ...
created: ...
answers: [
{
"k" : "53ac9a031703670858aff600",
"v" : "Yes"
},
{
"k" : "53b1e8961703670aa858e4ec",
"v" : "75731431"
},
...
{
"k" : "53b1e8961703670aa858e4ee",
"v" : "71825"
}
}

如何创建聚合匹配运算符,其中“53ac9a031703670858aff600”等于"is",“53b1e8961703670aa858e4ec”等于“75731431”使用 C# 驱动程序

我可以在 mongo shell 中运行以下查询并获得我要查找的结果:

db.Records.aggregate([{ "$match" : { 
"answers" : { "$elemMatch" : { "k" : "53ac9a031703670858aff600", "v" : "Yes" } },
"answers" : { "$elemMatch" : { "k" : "53b1e8961703670aa858e4ec", "v" : "75731431" } }
}}])

我尝试在 C# 中表达相同的查询,但由于重复的答案键而出现错误:

new BsonDocument("$match", new BsonDocument
{
{ "answers", new BsonDocument
{
{
"$elemMatch", new BsonDocument
{
{ "k", "53ac9a031703670858aff600" },
{ "v", "Yes" }
}
}
}
},
{ "answers", new BsonDocument
{
{
"$elemMatch", new BsonDocument
{
{ "k", "53b1e8961703670aa858e4ec" },
{ "v", "75731431" }
}
}
}
}
}

我曾尝试将单个 answers 元素与 $elemMatch 元素的 BsonArray 结合使用,但生成的 JSON 不返回任何结果。

如何使用 C# 驱动程序表达上述 $match 运算符?

最佳答案

看了Multiple $elemMatch expressions for matching array values using $all in MongoDB?之后应该有一个“answers”元素和一个 $all 来包装每个 $elemMatch。所以正确的 $match 运算符应该是:

db.Records.aggregate([{ "$match" : { 
"answers" : { "$all": [
{"$elemMatch" : { "k" : "53ac9a031703670858aff600", "v" : "Yes" } },
{ "$elemMatch" : { "k" : "53b1e8961703670aa858e4ec", "v" : "75731431" } }
]}
}}])

这使得 C# 代码看起来像这样:

new BsonDocument("$match", new BsonDocument
{
{ "answers", new BsonDocument
{
{
"$all", new BsonArray
{
new BsonDocument("$elemMatch", new BsonDocument
{
{ "k", "53ac9a031703670858aff600" },
{ "v", "Yes" }
}),
new BsonDocument("$elemMatch", new BsonDocument
{
{ "k", "53b1e8961703670aa858e4ec" },
{ "v", "75731431" }
})
}

}
}
}
}

关于c# - MongoDB C# 驱动程序 - $ 与相同字段匹配两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25006565/

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