Matthias
Matthias

Reputation: 164

MongoDB Select with QueryBuilder

i'm trying to select values from my database, but currently i'm unable to to it and although i know its the fact that the method doesnt except the QueryBuilder class as a parameter, i dont know what to do about it. I only found solutions for querys with one parameter or all parameters are not null. In my case i've a List with ID, and 4 parameters which dont have to be passed to the function so they could be null.

My current code looks like this.

collection = db.GetCollection<Datapoint>("test");

var query = new QueryBuilder<Datapoint>();
var queryattributes = new List<IMongoQuery>();
var ids = new List<IMongoQuery>();

// Add all Attributes if there
if (fromdate != null)
{
     BsonDateTime from = BsonDateTime.Create(fromdate);
     queryattributes.Add(Query.GTE("UTCTimestamp", from));
}
if (to != null)
{
    BsonDateTime bto = BsonDateTime.Create(to);
    queryattributes.Add(Query.LTE("UTCTimestamp", bto));
}
if (evId != null)
{
    queryattributes.Add(Query.EQ("EvId", evId));
}
if (evType != null)
{
    queryattributes.Add(Query.EQ("EvType", evType));
}

// Add all ID's
Parallel.ForEach(idList, data =>
{
    lock (query)
    {
        ids.Add(Query.EQ("CId", data));
    }
});

// But everything in the Query
query.Or(ids);

// Add Queryattributes if there
if (queryattributes.Count > 0)
{
    query.And(queryattributes);
}

var result = collection.FindAs<Datapoint>(query);

I'm trying to do it without Linq, since i found countless of test, which say that linq is much much slower, and since i want to run it as an Databasetest, i kinda need the performace to execute alot of querys.

The Linq query looks like this

var query2 =
    from e in collection.AsQueryable<Datapoint>()
    where idList.Contains(e.CId)
        && (evtId == null || e.EvId == evId)
        && (evType == null || e.EvType == evType.Value)
        && (fromdate == null || Query.GTE("UtcTimestamp", BsonDateTime.Create(fromdate)).Inject())
        && (to == null || Query.LT("UtcTimestamp", BsonDateTime.Create(to)).Inject())
    select e;

Upvotes: 2

Views: 8459

Answers (1)

i3arnon
i3arnon

Reputation: 116518

The QueryBuilder doesn't save a query inside it. You use it to generate a IMongoQuery and then use that query to actually query the database.

It seems the end of your code should look like this;

// But everything in the Query
IMongoQuery mongoQuery = query.Or(ids);

// Add Queryattributes if there
if (queryattributes.Count > 0)
{
    mongoQuery = query.And(queryattributes);
}

var result = collection.FindAs<Datapoint>(mongoQuery);

Upvotes: 1

Related Questions