[英]MongoDB - Pushing or Updating an element in Array
In products collection, i have an Array of recentviews
which has 2 fields viewedBy
& viewedDate
. 在产品集合中,我有一个
recentviews
数组,其中包含2个viewedBy
和viewedDate
。
I am on to $push
a fresh element in Array, so i am using below query :- 我要
$push
数组中的一个新元素,所以我正在使用下面的查询:-
db.produts.update( { _id: 'ObjectId("536c55bf9c8fb24c21000095")' },
{ $push: { recentviews: [ { viewedby: 'xyz', vieweddate: ISODate("2014-05-09T04:12:47.907Z") } ] } }
)
What is wrong in the above query? 上面的查询有什么问题?
Further If the record already exists for eg if there is already a record with viewedby
: xyz
, i need to update the record ie vieweddate
. 此外,如果该记录已经存在,例如,如果已经有一个记录,其
viewedby
: xyz
,我需要更新记录,即vieweddate
。
{ _id: 'ObjectId("536c55bf9c8fb24c21000095")' }
should be without quotes as with quotes it is treated as string instead of objectId, which is not equal to your primary key. { _id: 'ObjectId("536c55bf9c8fb24c21000095")' }
应该不带引号,因为带引号会将其视为字符串而不是objectId,这不等于您的主键。
{ _id: ObjectId("536c55bf9c8fb24c21000095") }
x1:PRIMARY> typeof( 'ObjectId("536c55bf9c8fb24c21000095")' )
string
x1:PRIMARY> typeof( ObjectId("536c55bf9c8fb24c21000095") )
object
You don't need to specify the brackets []
: 您无需指定方括号
[]
:
db.produts.update(
{ _id: ObjectId("536c55bf9c8fb24c21000095") },
{
"$push": {
"recentviews": {
"viewedby": "xyz",
"vieweddate": ISODate("2014-05-09T04:12:47.907Z")
}
}
}
)
So when adding a new sub-document to an array it is just specified that way and added to the array that is mentioned on the left side. 因此,在将新的子文档添加到数组时,只是以这种方式指定并添加到左侧提到的数组中。
Also your ObjectId
value was quoted which would have stopped the .update()
from matching. 还引用了您的
ObjectId
值,这将阻止.update()
的匹配。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.