我在一个文档中有一个(mongodb)嵌入式文档列表,我有兴趣在现有列表中添加一个新的嵌入式文档.
据我所研究,我可以使用$ addToSet,我无法弄清楚MongoDB是如何决定新文档是否已经存在于嵌入文档列表中或者是否是新文档,即MongoDB如何决定是否2个嵌入式文件是否相等?
ps我所拥有的嵌入式文档不仅仅是值,它们是非常复杂的结构,所以我想知道是否有任何地方我可以定义它们之间的平等意味着什么......
$addToSet
使用通常的mongodb相等规则:它将进行深入的值值比较,因此以下两个文档是相同的:
{ name: "John", hobbies: ["coding", "drinking", "chess"] } { hobbies: ["coding", "drinking", "chess"], name: "John" }
(文件内的订单不保证,所以它们是相同的)
而那些不是(成对):
// 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" }
请注意,这里没有特殊字段.您可以添加一个_id
字段,但它没有特殊的语义,并且将被视为与任何其他字段一样.