mongo可以更新阵列数据吗? [英] Can mongo upsert array data?
问题描述
我有一个像这样的mongo文档.
{
"_id" : ObjectId("50b429ba0e27b508d854483e"),
"array" : [
{
"id" : "1",
"letter" : "a"
},
{
"id" : "2",
"letter" : "b"
}
],
"tester" : "tom"
}
我希望能够使用单个mongo命令插入和更新array
,并且不要在find()
中使用条件,然后根据对象的存在运行insert()
和update()
.>
id
是我想成为选择器的项目.所以如果我用这个更新数组:
{
"id" : "2",
"letter" : "c"
}
我必须使用$set
语句
db.soup.update({
"tester":"tom",
'array.id': '2'
}, {
$set: {
'array.$.letter': 'c'
}
})
如果我想在数组中插入一个新对象
{
"id" : "3",
"letter" : "d"
}
我必须使用$push
语句
db.soup.update({
"tester":"tom"
}, {
$push: {
'array': {
"id": "3",
"letter": "d"
}
}
})
我需要一种用于数组项的upsert.
我是否必须以编程方式执行此操作,还是可以通过一个mongo调用来执行此操作?
我不知道在MongoDB 2.2上会向上插入嵌入式数组的选项,因此您可能必须在应用程序代码中进行处理.
鉴于您要将嵌入式数组视为一种虚拟集合,则可能需要考虑将数组建模为一个单独的集合.
您不能基于嵌入式数组中的字段值进行upsert,但可以使用 $addToSet
插入尚不存在的嵌入式文档:
db.soup.update({
"tester":"tom"
}, {
$addToSet: {
'array': {
"id": "3",
"letter": "d"
}
}
})
这不符合您通过数组元素id
进行匹配的确切用例,但是如果您知道期望的当前值,则可能会有用.
I have a mongo document like this.
{
"_id" : ObjectId("50b429ba0e27b508d854483e"),
"array" : [
{
"id" : "1",
"letter" : "a"
},
{
"id" : "2",
"letter" : "b"
}
],
"tester" : "tom"
}
I want to be able to insert and update the array
with a single mongo command and not use a conditional within a find()
then run insert()
and update()
depending on the presence of the object.
The id
is the item I want to be the selector. So if I update the array with this:
{
"id" : "2",
"letter" : "c"
}
I have to use a $set
statement
db.soup.update({
"tester":"tom",
'array.id': '2'
}, {
$set: {
'array.$.letter': 'c'
}
})
And if I want to insert a new object into the array
{
"id" : "3",
"letter" : "d"
}
I have to use a $push
statement
db.soup.update({
"tester":"tom"
}, {
$push: {
'array': {
"id": "3",
"letter": "d"
}
}
})
I need a sort of upsert for an array item.
Do I have to do this programmatically or can I do this with a single mongo call?
I'm not aware of an option that would upsert into an embedded array as at MongoDB 2.2, so you will likely have to handle this in your application code.
Given that you want to treat the embedded array as sort of a virtual collection, you may want to consider modelling the array as a separate collection instead.
You can't do an upsert based on a field value within an embedded array, but you could use $addToSet
to insert an embedded document if it doesn't exist already:
db.soup.update({
"tester":"tom"
}, {
$addToSet: {
'array': {
"id": "3",
"letter": "d"
}
}
})
That doesn't fit your exact use case of matching by id
of the array element, but may be useful if you know the expected current value.
这篇关于mongo可以更新阵列数据吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!