C# MongoDB是执行此查询最有效的方法
我有一个要求,当给定一个对象列表时,我需要排除数据库中已经存在的对象 我已经走上了传统的路线,迭代对象,一次检查一个对象是否存在于我的mongo集合中C# MongoDB是执行此查询最有效的方法,c#,performance,mongodb,mongodb-.net-driver,mongodb-query,C#,Performance,Mongodb,Mongodb .net Driver,Mongodb Query,我有一个要求,当给定一个对象列表时,我需要排除数据库中已经存在的对象 我已经走上了传统的路线,迭代对象,一次检查一个对象是否存在于我的mongo集合中 foreach (PickerPlace pickerPlace in param) { string id = pickerPlace.id; IMongoQuery query = Query<Place>.Where(p => p.Id == id); int count = this.contex
foreach (PickerPlace pickerPlace in param)
{
string id = pickerPlace.id;
IMongoQuery query = Query<Place>.Where(p => p.Id == id);
int count = this.context.Place.AsQueryable().Count(q => query.Inject());
if (count == 0)
{
filteredResults.Add(pickerPlace);
}
}
return filteredResults;
foreach(参数中的PickerPlace PickerPlace)
{
字符串id=pickerPlace.id;
IMongoQuery=query.Where(p=>p.Id==Id);
int count=this.context.Place.AsQueryable().count(q=>query.Inject());
如果(计数=0)
{
过滤器结果添加(pickerPlace);
}
}
返回筛选结果;
这是我想要实现的最有效的方式吗?不知怎的,我觉得我应该执行某种批处理操作
非常感谢
更新:
我发现以下代码的效率要高得多,但我仍然希望得到关于如何进一步改进的建议
List<string> ids = param.Select(p => p.id).ToList();
var results = this.context.Place.Find(Query.In("Id", new BsonArray(ids))).ToList();
List-id=param.Select(p=>p.id.ToList();
var results=this.context.Place.Find(Query.In(“Id”,新的BsonArray(Id))).ToList();
最有效的选择是:
var newIds = new HashSet<string>(param.Select(p => p.Id));
newIds.ExceptWith(
places.Find(Query<Place>.In(p => p.Id, newIds))
.SetFields(Fields<Place>.Include(p => p.Id))
.Select(p => p.Id));
var newIds=newhashset(param.Select(p=>p.Id));
newIds.ExceptWith(
查找(Query.In(p=>p.Id,newid))
.SetFields(Fields.Include(p=>p.Id))
.选择(p=>p.Id));
HashSet
使用项的GetHashCode(和Equals)实现高效比较。该查询在单个查询中返回所有现有项。设置字段
仅返回id,因此使用内置的\u id
索引(可能在RAM上),甚至不需要使用实际的数据文件