Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
270 views
in Technique[技术] by (71.8m points)

c# - MongoDb use filter to match a list

I have a list of BsonDocument:

   var list = db.GetCollection<BsonDocument>(collectionName); 
   var myIds = list.Find(_ => true)
    .Project(Builders<BsonDocument>.Projection.Include("_id"))
    .ToList();

that contains:

myIds = "{ 
{ "_id" : "cc9d9282-c9d2-4cba-a776-ffddsds274d5" },  
{ "_id" : "2c1ddd82-c9d2-4dda-afr6-d79ff1274d56" },  
{ "_id" : "ss969281-c9d2-4cba-a776-d79ffds274d5" }  
}"

And want to query like this:

var deleted =list.DeleteMany(Builders<MessageExchange>.Filter.In("_id", myIds));

I also have tried the following:

var filter = new BsonDocument("_id", new BsonDocument("$in", new BsonArray(myIds)));
var deleted = list.DeleteMany(filter);

Returns the attribute DeletedCount = 0 Could somebody point what seems to be wrong about the filter?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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));

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));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...