MongoDB Select中的多个逻辑条件 [英] Multiple Logical Conditions in MongoDB Select
问题描述
我需要基于多个条件查询集合
I need to Query a Collection based on Multiple Condition
我的收藏
{
"_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
我的C#代码:
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.
错误:
错误1'MongoDB.Driver.IMongoCollection' 不包含查找"的定义和最佳扩展方法 超载 'MongoDB.Driver.IMongoCollectionExtensions.Find(MongoDB.Driver.IMongoCollection, System.Linq.Expressions.Expression>, MongoDB.Driver.FindOptions)'有一些无效 参数....()
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 .... ()
条件:
var token = new {
Token = ObjectId("575f4e2efd14481598fc0ebf"),
UserToken = "101"
};
我需要检查令牌数据是否存在以及LastUpdate应该大于或等于(当前时间-15分钟)的一种情况.
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).
请帮助我.
推荐答案
Builder的类型必须与Collection的类型相同.就您而言,您有
Type of Builder must be same as type of Collection. in your case you have
集合作为EducationMetaModel.和建设者作为BsonDocument.保持一致.
根据您在过滤器中看到的内容,您可能只需
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");
与解析对象ID相比,将其作为字符串传递到过滤器还更好.像这样的东西
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"))
这篇关于MongoDB Select中的多个逻辑条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!