10

I have a list of (mongodb) Embedded Documents within one Document and I am interested in adding a new embedded document to the list of the existing ones.

As far as I have researched, I can use $addToSet, what I can't figure out is how does MongoDB decide if the new document already exists in the list of embedded documents or if it's a new one, i.e. how does MongoDB decide if 2 embedded documents are equal?

p.s. the embedded documents I have are not just values, they are quite complex structures, so I was wondering if there is any place I can define what the equality between 2 of them means...

Clara
  • 2,935
  • 6
  • 34
  • 49

1 Answers1

15

$addToSet uses the usual mongodb equality rules: it will do a deep value-by-value comparison, so the following two documents are identical:

{ name: "John", hobbies: ["coding", "drinking", "chess"] }
{ hobbies: ["coding", "drinking", "chess"], name: "John" }

(order within documents is not guaranteed, so they are identical)

while those aren't (pairwise):

// compare to:
{ name: "John", hobbies: ["chess", "coding", "drinking"] } 

// in arrays, the order matters:
{ name: "John", hobbies: ["coding", "drinking", "chess"] } 

// field names and values are case sensitive
{ Name: "John", hobbies: ["chess", "coding", "drinking"] } 
{ name: "john", hobbies: ["chess", "coding", "drinking"] } 

// additional field:
{ name: "John", lastName: "Doe", hobbies: ["chess", "coding", "drinking"] }

// missing field:
{ name: "John" }

Please note that there is no special field here. You can add an _id field, but it has no special semantics and will be treated just like any other field.

Community
  • 1
  • 1
mnemosyn
  • 45,391
  • 6
  • 76
  • 82
  • Thanks a lot for the comprehensive answer! I see! It sounds more like a dictionary comparison... – Clara Feb 05 '14 at 13:28
  • According to the [docs](https://docs.mongodb.com/manual/reference/operator/update/addToSet/#value-to-add-is-a-document) the fields order matters, though. Did something change or am I misunderstanding something? – mcont Jan 12 '22 at 15:05