假设您有一条mongo记录:
{
_id : 1234,
x: 12,
y: 34
}
我需要一个查询来更新特定的_id,
x = y;//assign the value of y to x
y = new Date().getTime();//assign current time to y
对于特定的_id。当前正在读取修改实体并更新它的id。是否可以在单个查询中完成?用猫鼬等于什么
最佳答案
除非使用$where
运算符,否则您不能这样做。但是您应该避免这样做,因为使用$where
可能会导致性能下降,如documentation中所述:
$ where评估JavaScript,无法利用索引。因此,当您使用标准MongoDB运算符(例如$ gt,$ in)表示查询时,查询性能会提高。
db.collection.update({ '$where': function() { return this.x === this.y }},
{'$set': { 'y': new Date().getTime() }}
)
最好的方法是像您一样运行两个查询。一个用于检索
_id
值,另一个用于更新文档。您不能使用单个MongoDB查询将
y
的值分配给x
并将new Date().getTime()
分配给y
。您首先需要使用y
方法检索.findOne()
值,然后使用另一个查询来更新文档。var y = db.collection.findOne({ '_id': <given ObjectId()> },
{ 'y': 1, '_id': 0 }
)['y'];
db.collection.update( { '_id': <given ObjectId()> },
{ '$set': { 'x': y, 'y': new Date().getTime() } }
)