I have this collection. I am trying to add object(item = {label: "Chrome", value: "chrome"}) to the array only if the value
is unique, i.e. insert the whole object, item
in the array foo
only if array foo
doesn't have any other object with the same value as item
, using one MongoDB operation
foo=[{label:"IE",value:"ie"},{label:"Firefox",value:"firefox"}]
i don't think $addToSet supports duplicate detection of object fields like you want. however you could do it like this:
first you match the parent object by id + that it doesn't contain "firefox" as the value in the foo object array. then you specify a
$push
to add your new object to the foo array. that way, no duplicates will be created in the foo array.not sure what your coding language is but here's the c# code that generated the above mongo query in case anybody's interested: