0

I'm trying to remove a single embedded document, I'm selecting and deleting like this

var collection = _database.GetCollection<BsonDocument>("MyCollection");
            var builder = Builders<BsonDocument>.Filter;
            var filter = builder.Eq("Name", varName)
                & builder.Eq("Thing01", varThing01);
                & builder.Eq("myembededarray.from", dateFrom)
                & builder.Eq("myembededarray.to", dateTo);

var result = collection.DeleteOneAsync(filter).Result;

but it's selecting and the deleting the entire record, not just the embedded document.

If I was not using the C# driver It looks like I could delete an embedded record by using the $pull operator, with something like

db.MyCollection.update( { Name: VarName }, { $pull: { myembededarray.from : { $eq: dateFrom },myembededarray.to : { $eq: dateTo } } } )

But I cant figure it out...

How do I use the $pull operator like this with c# ?

Solution was :

var collection = _database.GetCollection<BsonDocument>("MyCollection");
var builder = Builders<BsonDocument>.Filter;
//find the specific root document
var filter = builder.Eq("Name", varName)
           & builder.Eq("Thing01", varThing01);

//create a PullFilter to update the embedded document array
var update = Builders<BsonDocument>.Update.PullFilter("myembededarray",
Builders<BsonDocument>.Filter.Eq("from", dateFrom)
&Builders<BsonDocument>.Filter.Eq("to", dateTo));
//make an update (counter intuitively not a delete)
var result = collection.FindOneAndUpdateAsync(filter, update).Result;
Kickaha
  • 3,680
  • 6
  • 38
  • 57
  • `.Delete()` and `.Update()` are two completely different things. If you intend to use `.Update` then use it. And the `$pull` is meant to reference the "array" and not the "element within the array". The arguments "inside" the array reference work like a "query" on the array contents itself. Sort of like `$elemMatch` innards ,except you don't need to express `$elemMatch` within `$pull`. – Blakes Seven Mar 26 '16 at 02:39
  • @BlakesSeven That's not fair. You've closed this and referenced a question that does not help me. There is no clear way to do what I have asked. You have not helped me here. – Kickaha Mar 26 '16 at 02:48
  • It helps you perfectly. `PullFilter()` is what you want. Read it and follow the example. – Blakes Seven Mar 26 '16 at 02:53
  • @BlakesSeven, okay thanks I figured it out. The custom "T"ypes were tripping me up. And it's using an update to do a delete... which is semantically cruel. – Kickaha Mar 26 '16 at 03:22

0 Answers0