Using Asp.Net Core and MongoDB.Driver 2.13.0. I have a document (object id = 0000000000000000ec013401) with the following structure: an "lrec80" array of elements, the "RR4NFAD" property of array element contains an reference to a document in another collection.
{
"_id" : ObjectId("0000000000000000ec013401"),
"lrec80" : [
{
"RR4NFAD" : {
"$ref" : "RR4OCO",
"$id" : ObjectId("0000000000000000879866fd"),
"$db" : "tpfdf"
},
"RR4NCTY" : "LAX"
},
{
"RR4NFAD" : {
"$ref" : "RR4OCO",
"$id" : ObjectId("0000000000000000879866fd"),
"$db" : "tpfdf"
},
"RR4NCTY" : "SFO",
}}
I can delete the document in the other RR4OCO collection without any issue, but how do I delete one or more elements from the lrec80 array that have object ID references to that other deleted document?
For example, how would I remove elements from array lrec80 that have object IDs of "0000000000000000879866fd"?
I've tried the following without success:
var id = new ObjectId("0000000000000000ec013401");
var readFilter = Builders<BsonDocument>.Filter.Eq("_id", id);
var idToDelete = ObjectId.Parse("0000000000000000879866fd");
var deleteDoc = new BsonDocument {
{ "$id", idToDelete },
{ "$ref", "RR4OCO" },
{ "$db", "tpfdf" }
};
var deleteDoc2 =
new BsonDocument
{
{ "RR4NFAD", deleteDoc }
}
;
var deleteFilter = Builders<BsonDocument>.Update.Pull("lrec80", deleteDoc2);
_mongoCollection.UpdateOne(readFilter, deleteFilter, new UpdateOptions() { BypassDocumentValidation = true });
The error I get is:
QueryFailure flag was true (response was { "$err" : "MONG0025E 13.38.38 An error occurred when a request that contains '/PrefixedLREC/DFLREC/lrec80/RR4NFAD' was processed. Reason: Reference must be set using a DBRef that contains an ObjectID. Path name: /PrefixedLREC/DFLREC/lrec80/RR4NFAD." }).
I realize the error contains some details specific to my environment, but I'm still curious in general, how to query and remove all the array elements by matching the RR4NFAD.$id ObjectId.
Thanks for any help you can provide.