C# 和 MongoDB 使用 ObjectId 列表删除记录

标签 c# mongodb

我需要使用官方 C# 驱动程序从 mongo db 中的集合中删除一些记录。我的代码如下。

public static void Remove(List<ObjectId> objectIds)
{
        ObjectMongoCollection.Remove(Query.In("NotificationId", new BsonArray(objectIds)), SafeMode.True);
}

public class Notification
{
    public static MongoCollection<Notification> ObjectMongoCollection = MongoHelper.GetMongoServer("MongoKelimeYarisi").GetDatabase("KelimeYarisi").GetCollection<Notification>("Notification");

    [BsonId]
    public ObjectId NotificationId { get; set; }
    public int PlayerId { get; set; }
    public string OpponentName { get; set; }
    public string gameId { get; set; }
    public DateTime CreateDate { get; set; }
    public NotificationStatus Status = NotificationStatus.New;
    public NotificationType Type = NotificationType.RoundSubmit;
    public bool IsPushed { get; set; }

它运行没有错误,但似乎不起作用。如何使用 ObjectId 列表删除记录。

也试过:

ObjectMongoCollection.Remove(Query.In("_id", new BsonArray(objectIds)), SafeMode.True);

最佳答案

我使用了一种不同的方法来获取 mongo 查询并且有效。我构建了一个 linq 查询并将其转换为 mongo 查询。

    public static void Remove(List<ObjectId> objectIds)
    {
        var linqQuery = from n in ObjectMongoCollection.AsQueryable<Notification>() where n.NotificationId.In(objectIds) select n;
        var mongoQuery = ((MongoQueryable<Notification>)linqQuery).GetMongoQuery();       
        ObjectMongoCollection.Remove(mongoQuery);
    }

关于C# 和 MongoDB 使用 ObjectId 列表删除记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12199444/

相关文章:

Java 3.0 从 mongodb 列中获取不同的值

node.js - 在mongodb中创建不同类型的用户

javascript - 如何使用 node.js 结合基于 id(transectionid) 的两个集合?

c# - Math.Floor 或 Math.Truncate 与 (int) 在正数性能方面

c# - 模拟 DbContext - 无法插入新对象

c# - 在 system.net 中增加 "maxconnection"设置有什么缺点吗?

php - 如何在管理类中将函数作为参数传递

c# - 执行 : Manual addressing is enabled on this factory, 时出现 WCF 错误,因此发送的所有消息都必须预先寻址

c# - 在 C# 中为 block blob 生成共享访问签名

java - 使用 MongoOperation 在 Spring Data MongoDB 中构建 ArrayFilters 更新