c# - 根据内部对象数组对 Mongo DB 结果进行排序
问题描述
我们的集合中有以下文档结构:
{
Title: "Some product",
Prices:[{
Currency: "GBP",
Value: 10
},
{
Currency: "USD",
Value: 15
}
]
}
我们正在尝试使用 C# BSON 驱动程序根据特定货币的价格订购这些文档:
sort = Builders<ProductSearchData>.Sort.Ascending(x => x.Prices.First(x=>x.Currency == currency).Value);
然后我们将它传递给集合:
var results = await Collection.FindAsync(filter, new FindOptions<ProductSearchData>
{
Sort = sort,
Skip = page*pageSize,
Limit = pageSize
});
然而,这并没有给出正确的排序顺序。相反,值似乎随机返回。上面的语法是正确的还是我们应该以不同的方式查询?
如果我们做一个更简单的排序,例如
sort = Builders<ProductSearchData>.Sort.Descending(x => x.Title);
一切正常。
通过登录 Mongo,我们似乎得到了这两个查询:
"{ "find" : "ProductSearch", "filter" : { "Prices" : { "$elemMatch" : { "Currency" : 10, "Value" : { "$gte" : 0, "$lte" : 10000 } } }, "IsActive" : true }, "sort" : { "Value" : 1 }, "skip" : 0, "limit" : 10, "$db" : "MyForest_Data", "lsid" : { "id" : CSUUID("d4caa989-9493-41a7-bcde-81f198beda7a") } }"
{ "aggregate" : "ProductSearch", "pipeline" : [{ "$match" : { "Prices" : { "$elemMatch" : { "Currency" : 10, "Value" : { "$gte" : 0, "$lte" : 10000 } } }, "IsActive" : true } }, { "$group" : { "_id" : 1, "n" : { "$sum" : 1 } } }], "cursor" : { }, "$db" : "MyForest_Data", "lsid" : { "id" : CSUUID("d4caa989-9493-41a7-bcde-81f198beda7a") } }
解决方案
怎么样:
collection.AsQueryable()
.SelectMany(x => x.Prices, (x, pr) => new { T = x.Title, V = pr.Value, C = pr.Currency } )
.Where(x => x.C == "GBP")
.OrderBy(x => x.V)
.Skip(0)
.Take(100)
- 跳过并采取分页...
推荐阅读
- angular - 如何检测父元素/组件的类
- css - 如何获取最后一个子 *ngFor 组件列表
- php - 如何访问 PHP 对象的元素
- python - docker找不到docker命令的mountend套接字
- javascript - console.log() 在 Firefox 中不起作用,但在 IE 中不起作用
- javascript - 如何将样式从计算传递到模板
- javascript - SyntaxError:Firefox 中的正则表达式组无效。但是在 chrome 中工作
- java - 如何计算当前系统时间和存储时间间隔
- r - R:将列与作为列表对象存在的另一列中的值进行比较
- python - 添加超范围;如何?