2016-01-22 87 views
1

字段的值赋给另一个假设你有一个蒙戈记录:如何在一个蒙戈查询

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

回答

1

你不能这样做,除非你使用$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的值分配给xnew 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() } } 
)