如何在单个mongo查询中将字段的值分配给另一个字段

假设你有一个mongologging:

{ _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.current.currentCurrently我正在读取修改实体和更新它的id。这是可能做到这一点在一个单一的查询? 使用mongoose会是什么样子?

除非使用$where操作符,否则不能这样做。 但是你应该避免这样做,因为使用$where可能会导致文档中提到的性能下降:

$在评估JavaScript,不能利用索引。 因此,使用标准MongoDB运算符(例如$ gt,$ in)表示查询时,查询性能得到改善。

 db.collection.update({ '$where': function() { return this.x === this.y }}, {'$set': { 'y': new Date().getTime() }} ) 

最好的方法是像你一样运行两个查询。 一个检索_id值,另一个更新您的文档。

您不能将y的值赋给x并且使用一个MongoDB查询将new Date().getTime()赋值给y 。 您需要先使用.findOne()方法检索y值,然后使用另一个查询来更新文档。

 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() } } )