首页 > 解决方案 > 根据内部对象数组对 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") } }

标签: c#mongodbmongodb-querymongodb-.net-driver

解决方案


怎么样:

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)
  • 跳过并采取分页...

推荐阅读