MongoDB filter query in .net converting from SQL

Viewed 444

I am trying to convert a basic query from SQL to Mongo, this is the SQL:

select top(1)* from x where(a = 5) and(b = 6) and (c = 11) order by d desc

What I have so far:

var builder = Builders<BsonDocument>.Filter;
var filter = builder.Eq("a", 5) & builder.Eq("b", 6) & builder.Eq("c", 11);
List<BsonDocument> i = getCollection("x").Find(filter).ToList();
if (i.Count > 0)
{
   id = i[0].GetElement("id").Value.ToInt32();
}
return id;

i is empty, the DB contains the required data, any help greatly appreciated!

2 Answers

i can't stand bsondocuments in c#, so i'd create a class for mapping like this:

    public class Item
    {
        public int a { get; set; }
        public int b { get; set; }
        public int c { get; set; }
        public int d { get; set; }
    }

and then issue a find query like this:

    var filter = Builders<Item>.Filter.Where(i => i.a == 5 && i.b == 6 && i.c == 11);
    var sort = Builders<Item>.Sort.Descending(i => i.d);
    var projection = Builders<Item>.Projection.Expression(i => i.id);

    var id = collection.Find(filter)
                       .Sort(sort)
                       .Limit(1)
                       .Project(projection)                               
                       .ToList()
                       .SingleOrDefault();

here's an alternative way to do it without the added noise of builders.

This is how I am successfully getting required response:

var filter = "{$and : [{a : 5},{b : 6},{c : 11}]}";
SortDefinition<BsonDocument> sort = Builders<BsonDocument>.Sort.Descending("d");
List<BsonDocument> l = getCollection("x").Find(filter).Sort(sort).Limit(1).ToList();
Related