MongoDB-嵌入式文档列表上的$ addToSet [英] MongoDB - $addToSet on a list of Embedded Document

查看:91
本文介绍了MongoDB-嵌入式文档列表上的$ addToSet的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个文档中有一个(mongodb)嵌入式文档列表,并且我有兴趣在现有文档列表中添加一个新的嵌入式文档.

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.

据我研究,我可以使用$ addToSet,我不知道的是MongoDB如何确定嵌入式文档列表中是否已经存在新文档,或者它是一个新文档,即如何MongoDB决定两个嵌入式文档是否相等?

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.我拥有的嵌入式文档不仅是值,而且是相当复杂的结构,所以我想知道是否可以定义其中两个相等的含义是什么?

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...

推荐答案

$addToSet使用常规的

$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)

不是(成对)的

// 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字段,但是它没有特殊的语义,将像其他任何字段一样对待.

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.

这篇关于MongoDB-嵌入式文档列表上的$ addToSet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆