I have a MongoDB database on Atlas that keeps details of books I have read. There are two collections: an authors one and a books one.
[BsonIgnoreExtraElements]
public class Author
{
[BsonId][BsonRepresentation(BsonType.ObjectId)] public ObjectId _id { get; set; }
[BsonElement("first")] public string? first { get; set; }
[BsonElement("last")] public string? last { get; set; }
[BsonElement("author_id")] public BsonInt32? author_id { get; set; }
[BsonElement("FullName")][BsonIgnoreIfNull] public string? FullName { get; set; }
}
[BsonIgnoreExtraElements]
public class Book
{
[BsonId][BsonRepresentation(BsonType.ObjectId)] public ObjectId _id { get; set; }
[BsonElement("title")] public string? title { get; set; }
[BsonElement("title_id")] public BsonInt32? title_id { get; set; }
[BsonElement("author")] public string? author { get; set; }
[BsonElement("issue_date")] public string? issue_date { get; set; }
[BsonElement("return_date")] public string? return_date { get; set; }
}
There are 485 authors and 1452 books. The database provides data for an Android app created using MAUI. One of the pages provides a list of which authors have the most books in the database. This uses a LINQ group query.
public async Task<List<Popular>> GetPopular()
{
IMongoQueryable<Popular>? query = (from book in booksCollection.AsQueryable()
group book by book.author into g
let lastBook = g.OrderByDescending(b => b.return_date).FirstOrDefault()
select new Popular
{
Author = g.Key,
Count = g.Count(),
ReturnDate = lastBook.return_date,
Title = lastBook.title
}).OrderByDescending(g => g.Count).ThenBy(g => g.Author).Take(10);
List<Popular>? popular = await query.ToListAsync();
return popular;
}
A lot of the time this runs correctly and produces the list. However it does crash on the query.ToListAsync statement at random.
**MongoDB.Driver.Linq.Linq3Implementation.Ast.Optimizers.AstGroupingPipelineOptimizer+UnableToRemoveReferenceToElementsException:**
'Exception of type 'MongoDB.Driver.Linq.Linq3Implementation.Ast.Optimizers.AstGroupingPipelineOptimizer+UnableToRemoveReferenceToElementsException' was thrown.'
I’m using Visual Studio 17.11.4 with MongoDB.Driver 2.9 that has LINQ 3 as the default. Is there an easy way to convert the query to use Builders or BsonDocument, or is there an error in the LINQ I’ve used?
1
I sorted this out with the aid of Studio3T (3T Software Labs Ltd https://studio3t.com). This is an excellent product for building queries for MongoDB with Free and Pro versions. I’ve replaced the linq with a BsonDocument query that doesn’t crash!