I have a collection like this (I removed fields that are not related to the question)
{
_id:ObjectId('5dd7d946cd9c645f1cdc21ef'),
Versions: [
{
"Barcode" : "200830001128132700636"
},
{
"Barcode" : "200830001128132700637"
}
]
},
{
_id:ObjectId('5dd7d946cd9c645f1cdc21eg'),
Versions: [
{
"Barcode" : "200830001128132700638"
},
{
"Barcode" : "200830001128132700639"
}
]
}
I need to find the greatest (max) barcode in the whole collection.
I tried with a code like this:
var options = new FindOptions<Document>
{
Limit = 1,
Sort = Builders<Document>.Sort.Descending(d => d.Versions.Select(v => v.BarCode).Aggregate((v1, v2) => string.Compare(v1, v2) > 0 ? v1 : v2))
};
using var results = await _context.DocumentiItems.FindAsync(FilterDefinition<Document>.Empty, options);
But I get ArgumentNullException, I think it's unable to traslate the expression with the aggregate.
Can you suggest me a better approach?, if possible I want to avoid the use of BSON strings and use only labmda expressions.
The type of is DocumentiItems is IMongoCollection<Document>
this can be easily achieved with the AsQueryable()
interface like so:
var result = collection.AsQueryable()
.SelectMany(i => i.Versions)
.OrderByDescending(v => v.Barcode)
.Take(1)
.Single();
here's a test program:
using MongoDB.Entities; using MongoDB.Entities.Core; using System; using System.Linq; namespace StackOverflow { public class Item : Entity { public Version[] Versions { get; set; } } public class Version { public string Barcode { get; set; } } public class Program { private static void Main(string[] args) { new DB("test", "localhost"); var result = DB.Queryable<Item>() .SelectMany(i => i.Versions) .OrderByDescending(v => v.Barcode) .Take(1) .Single(); Console.WriteLine($"max barcode: {result.Barcode}"); Console.Read(); } } }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.