[英]Find MongoDB document and only matching array elements w/ C# driver
I'm trying to return a document, and that document should have it's array filtered such that it only contains one item.我正在尝试返回一个文档,并且该文档应该对其进行数组过滤,使其仅包含一项。 I've seen many similar questions, but none of them deal with dynamic queries.我见过很多类似的问题,但没有一个涉及动态查询。 There may be several constraints so I have to be able to keep adding to the filter.可能有几个限制,所以我必须能够继续添加到过滤器中。
{
"_id" : ObjectId("6058f722e9e41a3d243258dc"),
"fooName" : "foo1",
"fooCode" : 1,
"bar" : [
{
"barCode" : "123",
"barName" : "Rick's Cafe",
"baz" : [
{
"bazId" : "00",
"bazDescription" : "Ilsa"
},
{
"bazId" : "21",
"bazDescription" : "Victor"
}
]
},
{
"barCode" : "456",
"barName" : "Draco Tavern",
"baz" : [
{
"bazId" : "00",
"bazDescription" : "Rick Shumann"
}
]
}
]
}
This is my attempt, it returns a document who's array contains the barCode, and the array's entire contents are included.这是我的尝试,它返回一个包含条形码的数组的文档,并且包含数组的全部内容。
Expression<Func<Foo, bool>> filter = x => x.FooCode == 1;
string barCode = "456"
if (!String.IsNullOrEmpty(barCode))
{
Expression<Func<Foo, bool>> newPred =
x => x.Bar.Any(s => s.BarCode == barCode);
filter = filter.CombineAnd(newPred);
}
var fooQuery =
_fooCollection
.Find(filter);
How do I remove non-matching array elements, but only if an array element was specified?如何删除不匹配的数组元素,但前提是指定了数组元素?
You need to use aggregate in MongoDB.您需要在 MongoDB 中使用聚合。 You can split the array elements with unwind , filter with match , select the keys that you want with project and group with common column like id or something.您可以使用unwind拆分数组元素,使用match过滤,select 使用project和group所需的键,例如 id 或其他内容。
MongoDB Aggregation docs: https://docs.mongodb.com/manual/aggregation/ MongoDB 聚合文档: https://docs.mongodb.com/manual/aggregation/
Unwind
to convert the single document into a document per nested-array element in the shape of: Unwind
以将单个文档转换为每个嵌套数组元素的文档,其形状为:{
"_id" : ObjectId("6058f722e9e41a3d243258dc"),
"fooName" : "foo1",
"fooCode" : 1,
"bar": {
"barCode" : "123",
"barName" : "Rick's Cafe",
...
}
}
Match
to find the element you want Match
以找到您想要的元素Group
to recombine the nested-array Group
以重新组合嵌套数组So the resulting C# might look like:因此生成的 C# 可能如下所示:
var fooQuery = _fooCollection.Aggregate()
.Unwind("bar")
.Match(BsonDocument.Parse("{ 'bar.barcode': '"+ barCode + "'}"))
.Group(BsonDocument.Parse("{ '_id':'$fooCode' }"))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.