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
529 views
in Technique[技术] by (71.8m points)

c# - MongoDB .Net driver 2.0 Pull (remove element)

Can you help me to run correctly "Pull (remove)" with 2.0 driver.

I have a collection like this and I want to remove first follower named as fethiye by follower field.

{
  "_id": ObjectId("554e05dfc90d3d4dfcaa2aea"),
  "username": "bodrum",
  "followerList": [
    {
      "_id": ObjectId("554e0625a51586362c33c6df"),
      "follower": "fethiye",
      "avatar": "fethiye.png"
    },
    {
      "_id": ObjectId("554e0625a51586362c33c6df"),
      "follower": "izmir",
      "avatar": "izmir.png"
    }
  ]
} 

How can I fix this query?

var filter = new BsonDocument("username", "bodrum");
var update = Builders<Person>.Update.Pull("followerList:follower", "fethiye");
Person pr = collection.FindOneAndUpdateAsync(filter, update).Result;

Thanks.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

When using a filter to remove array elements, you need to use the PullFilter builder instead of Pull (which matches whole elements).

var collection = db.GetCollection<Person>("people");
var filter = new BsonDocument("username", "bodrum");
var update = Builders<Person>.Update.PullFilter("followerList",
    Builders<Follower>.Filter.Eq("follower", "fethiye"));
var result = collection.FindOneAndUpdateAsync(filter, update).Result;

Or somewhat more succinctly, using lambdas:

var update = Builders<Person>.Update.PullFilter(p => p.followerList,
                                                f => f.follower == "fethiye");
var result = collection
    .FindOneAndUpdateAsync(p => p.username == "bodrum", update).Result;

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

...