Multiple Logical Conditions in MongoDB Select

2019-08-14 08:54发布

问题:

I need to Query a Collection based on Multiple Condition

My Collection

{
    "_id" : ObjectId("575f4e2efd14481598fc0ebf"),
    "Emp_ID" : "100",
    "LastUpdate" : ISODate("2016-06-13T18:30:00.000Z")
},
{
    "_id" : ObjectId("575f4e2efd14481598fc0ebf"),
    "Emp_ID" : "101",
    "LastUpdate" : ISODate("2016-06-14T06:33:00.000Z")
}, ... ()

Now I need to Check the document is exist or not based on my below condition

My C# Code:

private static IMongoClient _client;
private static IMongoDatabase _database;

_client = new MongoClient();
_database = _client.GetDatabase("Test");

var collection = _database.GetCollection<EducationMetaModel>("EmpLog");

var filterBuilder = Builders<BsonDocument>.Filter;
var filter = filterBuilder.Eq("_id", token.Token) 
                 & filterBuilder.Eq("Emp_ID", token.UserToken) 
                 & filterBuilder.Gte("LastUpdate", DateTime.UtcNow.Add(new TimeSpan(0, -15, 0)));

var cItem = collection.Find(filter);

But I'm getting build error from the above code. Kindly assist me. I need to check the document is available or not based on filter.

Error:

Error 1 'MongoDB.Driver.IMongoCollection' does not contain a definition for 'Find' and the best extension method overload 'MongoDB.Driver.IMongoCollectionExtensions.Find(MongoDB.Driver.IMongoCollection, System.Linq.Expressions.Expression>, MongoDB.Driver.FindOptions)' has some invalid arguments .... ()

Condition:

var token = new {
    Token = ObjectId("575f4e2efd14481598fc0ebf"),
    UserToken = "101"
};

I need to check the token data is present along with one condition the LastUpdate should be greater than or equal to (Current Time - 15 Mins).

Kindly assist me.

回答1:

Type of Builder must be same as type of Collection. in your case you have

collection as EducationMetaModel. and builder as BsonDocument. keep these consistent.
From what I can see in your filter, you could just have

  var collection = _database.GetCollection<BsonDocument>("EmpLog");

Also you're better off parsing object id than passing it as a string to your filter. something like this

var filter = filterBuilder.Eq("_id", ObjectId.Parse("57623ed9adb381a5cc0d1994"))