MongoDb使用过滤器匹配列表 [英] MongoDb use filter to match a list
本文介绍了MongoDb使用过滤器匹配列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个BsonDocument
的列表:
var list = db.GetCollection<BsonDocument>(collectionName);
var myIds = list.Find(_ => true)
.Project(Builders<BsonDocument>.Projection.Include("_id"))
.ToList();
其中包含:
myIds = "{
{ "_id" : "cc9d9282-c9d2-4cba-a776-ffddsds274d5" },
{ "_id" : "2c1ddd82-c9d2-4dda-afr6-d79ff1274d56" },
{ "_id" : "ss969281-c9d2-4cba-a776-d79ffds274d5" }
}"
并想这样查询:
var deleted =list.DeleteMany(Builders<MessageExchange>.Filter.In("_id", myIds));
我也尝试了以下方法:
var filter = new BsonDocument("_id", new BsonDocument("$in", new BsonArray(myIds)));
var deleted = list.DeleteMany(filter);
返回属性DeletedCount = 0
有人可以指出过滤器似乎有什么问题吗?
Returns the attribute DeletedCount = 0
Could somebody point what seems to be wrong about the filter?
推荐答案
您必须像这样从BsonDocument中提取 _id :
You'll have to extract the _id from the BsonDocument like this:
var extractedIds = myIds.Select(x => x["_id"].ToString()).ToList();
之后,您可以在过滤器中使用它.
After which you can use it in the filter.
list.DeleteMany(Builders<MessageExchange>.Filter.In("_id", extractedIds));
确保过滤器的 _id 部分与MessageExchange类的部分匹配
Make sure that the _id part of the filter matches that of the MessageExchange class
另一种方法是使它成为强类型:
Another way to do so is by making it strong typed:
list.DeleteMany(Builders<MessageExchange>.Filter.In(x => x.Id, extractedIds));
这篇关于MongoDb使用过滤器匹配列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文