Using both $in and $elemMatch using the C# Driver

岁酱吖の 提交于 2020-01-06 12:53:54

问题


I'm having a hard time translating a working MongoDB query to the C# driver's untyped equivalent. The query:

{
    "Field" : { "$elemMatch" : { "$in" : ["Hamster"]}}
}

What I have:

Query.ElemMatch("Field", Query.In("", new BsonArray(new[] { "Hamster" })));

Which generates:

{
    "Field" : { "$elemMatch" : { "" : { "$in" : ["Hamster"] }}}
}

That's pretty close but i can't figure out how to remove the name from the $in query.


回答1:


It seems like it should be possible, but the way the helper methods are structured I can't see an easy way of constructing that query directly.

The only way I could recreate the desired query is by doing variations of the following:

var queryDocument = QueryDocument.Parse("{\"$in\" : [\"Hamster\"]}");
var nestedQueryDocument = Query.ElemMatch("Field", new QueryDocument(queryDocument));

Creates the following output

{
    "Field" : { "$elemMatch" : { "$in" : ["Hamster"]}}
}

Not the most elegant of solutions though.




回答2:


Query.ElemMatch("Field", new QueryDocument("$in", new BsonArray(new[] { "Hamster" })));


来源:https://stackoverflow.com/questions/22176263/using-both-in-and-elemmatch-using-the-c-sharp-driver

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!