Delete(Expression<Func<T, bool>> criteria) Mongo
本文关键字:gt lt bool criteria Mongo Func Expression Delete | 更新日期: 2023-09-27 18:33:35
是否可以执行查询Expression<Func<T, bool>>
并删除找到的所有文档?我使用的是mongoDB c#驱动程序,我从mongo存储库中获取了这个想法,但我没有在我的实体上继承任何基类,所以我没有类和对通用属性"id"的访问权限
以下代码不起作用:
foreach (T entity in this.collection.AsQueryable<T>().Where(criteria))
{
this.Delete(entity.Id);
}
有什么建议吗?
您应该能够将查询传递给Remove
。例如,删除具有值为 "test123"
的 name
属性的所有文档:
collection.Remove(Query.EQ("name", "test123"));
这样,只需一次调用即可删除所有匹配的文档,而不是先获取匹配项,然后单独删除它们(甚至使用 $in
运算符作为一个组删除)。
您可以创建以下通用扩展方法来删除符合条件的所有文档。但是集合的 Remove 方法需要一些 MongoQuery 来查找应该删除的文档。如果要传递 id 选择器,您可以构造按 id 选择文档的查询:
public static void RemoveAll<T>(this MongoCollection<T> collection,
Expression<Func<T, bool>> criteria, Func<T, BsonValue> idSelector)
{
foreach (T entity in collection.AsQueryable<T>().Where(criteria))
collection.Remove(Query.EQ("_id", idSelector(entity)));
}
用法:
people.RemoveAll(p => p.Age > 50, p => p.Id);
你可以使用这个:
collection.Remove(Query<T>.Where(criteria));