2

是否可以进行查询 Expression<Func<T, bool>>并删除找到的所有文档?我正在使用 mongoDB c# 驱动程序,我从 mongo 存储库中获取了这个想法,但我没有在我的实体上继承任何基类,所以我没有类和对通用属性“id”的访问权限

以下代码将不起作用:

foreach (T entity in this.collection.AsQueryable<T>().Where(criteria))
{
    this.Delete(entity.Id);
}

有什么建议吗?

4

3 回答 3

2

您应该能够将查询传递给Remove. 例如,删除所有具有namevalue 属性的文档"test123"

collection.Remove(Query.EQ("name", "test123"));

这样,只需一次调用即可删除所有匹配的文档,而不是先获取匹配项,然后单独删除它们(甚至使用$in运算符作为一个组删除)。

于 2013-10-02T21:47:50.753 回答
0

您可以创建以下通用扩展方法来删除所有符合您的条件的文档。但是集合的 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);
于 2013-10-02T21:58:32.333 回答
0

你可以使用这个:

collection.Remove(Query<T>.Where(criteria));
于 2014-11-16T13:17:04.643 回答