假设我有一组调查回复文档,如下所示:
{
_id: ...
surveryId: ...
created: ...
answers: [
{
"k" : "53ac9a031703670858aff600",
"v" : "Yes"
},
{
"k" : "53b1e8961703670aa858e4ec",
"v" : "75731431"
},
...
{
"k" : "53b1e8961703670aa858e4ee",
"v" : "71825"
}
}
我如何创建聚合匹配运算符,其中“53ac9a031703670858aff600”等于“是”,“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" }
}
}
}
}
}
我尝试使用带有$ elemMatch元素的BsonArray的单个answer元素,但生成的JSON不会返回任何结果。
如何使用C#驱动程序表达上述$ match运算符?
答案 0 :(得分:2)
在看了Multiple $elemMatch expressions for matching array values using $all in MongoDB?后,应该有一个“答案”元素和一个$ 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" }
})
}
}
}
}
}
答案 1 :(得分:0)
尝试
var query = Query.And(
Query.EQ("Field1", "somevalue"),
Query.EQ("Field2", "somevalue")
);
或
var query = from e in collection.AsQueryable<Person>()
where e.Field1 == "someval" &&
e.Field2 == "someotherVal"
select e;
如果需要,您可以进一步循环
foreach (var thing in query)
{
/// access thing
}
或使用光标
var cursor = collection.FindAs<BsonDocument>(Query.EQ("field1", "value"));
cursor.SetFields(Fields.Include("otherfield"));
var items = cursor.ToList();
还有其他方法,但今天一切......