使用非通用EQ-Query从集合中删除文档

本文关键字:删除 文档 集合 EQ-Query | 更新日期: 2023-09-27 18:03:54

我试图使用非通用EQ-Query从我的集合中删除文档,但它没有删除任何内容。使用泛型EQ-Query,文档被成功删除。

这是我在MongoDB中存储的对象。

public class UserDto {
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string UserName { get; set; }
}

下面是我如何从集合中删除文档的示例代码。

var collection = database.GetCollection<UserDto>(typeof(UserDto).Name);
var single = collection.AsQueryable<UserDto>().FirstOrDefault(p => p.Id == 46);
// using the generic version will remove the document.
//var result = collection.Remove(Query<UserDto>.EQ(p => p.Id, 46));
// using the non-generic version will not remove the document.
var result = collection.Remove(Query.EQ("Id", BsonValue.Create(46)));

是否有什么错误的设置我的MongoQuery删除文档?

我正在使用MongoDB 2.6.1和MongoDB Driver c# 1.9.1.221

使用非通用EQ-Query从集合中删除文档

如果您没有配置,那么您的Id字段将被驱动程序视为文档的Id。这意味着MongoDB中的字段将是"_id"而不是"Id"。

当你使用通用查询时,驱动程序会为你做翻译。非通用查询应该如下所示:

var result = collection.Remove(Query.EQ("_id", 46));