在MongoDB中按索引将子文档中的字段向上插入数组中 [英] upsert a field in a subdocument in an array by index in MongoDB
问题描述
我具有以下MongoDB结构
I have the following MongoDB structure
{
_id : ...,
other_stuff ... ,
my_array : [
{ title: ...., body: ...., email: .... },
{ title: ...., body: ...., email: .... },
{ title: ...., body: ...., email: .... }
]
}
我需要在"my_array"字段中的子文档中更新/或插入(如果不存在)名为"click_number"的字段.如果"click_number"字段不存在,请插入该字段并将其设置为1;否则,将其设置为1.如果存在,将其增加1.
I need to update/or insert (if not existent) a field called "click_number" in the subdocument within the "my_array" field. If the "click_number" field is not existent, insert the field and set it to 1; if existent, increment it by 1.
首先,我不知道如何通过其索引更新数组元素,其次,我不知道如何根据字段的存在进行更新或插入.感谢您的帮助
First of all, I don't know how to update an array element by its index, and secondly, I do not know how to do update or insert depending on the existence of the field. I appreciate your help
推荐答案
您要在集合上使用update
命令,如下所示(示例):
You want to use the update
command on your collection as follows (example):
db.collection.update(
{ "my_array.title" : "title_one" },
{ $inc : { "my_array.$.click_number" : 1 } }
);
发生了什么事?
在update
的第一个参数上,定义一个query
以匹配要更新的文档.我们在名为my_array
的数组中搜索名为title
的属性.您当然可以通过将点表示法修改为"my_array.email"
来匹配body
或email
.
On the first parameter of update
you define a query
to match documents you wish to update. We search for a property named title
inside the array called my_array
. You could match against body
or email
of course by modifying the dot notation to: "my_array.email"
.
第二个参数定义更新,即要应用的修改.我们有一个$inc
运算符来递增字段,我们在此语句中使用了该字段. query
选择具有匹配数组元素的文档.您可以使用$
表示法来获取此匹配的数组项. "my_array.$"
选择匹配的数组元素,该元素具有title
,email
和body
.如果您尝试给不存在的字段赋值,MongoDB会为您做到这一点.如果该字段不存在,则$inc
将该字段设置为指定的数量. $inc
运算符接受正数和负数的增量.
The second parameter defines the update, the modification to apply. We have a $inc
operator to increment fields, which we use in this statement. The query
selects a document with the matched array element. You can reach for this matched array item with the $
notation. The "my_array.$"
selects the matched array element, which has a title
, email
and body
. If you try to give value to a non existing field, MongoDB will do it for you. If the field does not exist, $inc
sets the field to the specified amount. The $inc
operator accepts positive and negative incremental amounts.
另一个例子:
db.collection.update(
{ _id : "john", "my_array.email" : "email" },
{ $inc : { "my_array.$.click_number" : 1 } }
);
这篇关于在MongoDB中按索引将子文档中的字段向上插入数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!