I'm new to MongoDB and have been struggling with this a bit. Let's say I have a document with an id, name, and array of objects:
{
"_id": {
"$oid": "614ba49b46727413d60b99e2"
},
"Name": 1,
"ObjectArray": [
{
"ObjectId": {
"$oid": "614ba49b46727413d60b99e3"
},
"Value": "some value",
},
{
"ObjectId": {
"$oid": "614ba49b46727413d60b99e5"
},
"Value": "other value",
}
],
}
I have a C# class that maps to this document and everything works in that regard. Let's say I want to add another object to the object array only if the new object's Id doesn't already exist in the array? I'm using C# Driver for this and have tried several things.
I've tried several ideas including the following --
var filter = FilterBuilder.Eq(x => x.Id, id) &
FilterBuilder.Nin(x => x.ObjectArray[-1].ObjectId, new[] { newDoc.ObjectId});
This unfortunately only checks the first object in the object array. So as asked before how do I only add a new object to an array if a condition exists all within one filter?
Thanks for your time.
*** Solution ***
Used Elematch in conjunction with Not to do the filtering all in one.
var filter = FilterBuilder.Eq(x => x.Id, id) &
FilterBuilder.Not(FilterBuilder.ElemMatch(x => x.ObjectArray,
Builders<ObjectClass>.Filter.Eq(y => y.ObjectId, newDoc.ObjectId)));