akhil
akhil

Reputation: 143

How to assign the value of a field to another in a single mongo Query

Suppose you have a mongo record :

{
    _id : 1234,
    x: 12,
    y: 34
}

I need a query that will update an particular _id in such a way that

x = y;//assign the value of y to x
y = new Date().getTime();//assign current time to y

for a particular _id.currently I am reading the id modifying the entity and updating it.Is this possible to do it in a single query? what would be it's equivalent using Mongoose

Upvotes: 1

Views: 71

Answers (1)

Sede
Sede

Reputation: 61253

You can't do that unless you use the $where operator. But you should avoid doing this because using $where may cause a drop of performance as mentioned in the documentation:

$where evaluates JavaScript and cannot take advantage of indexes. Therefore, query performance improves when you express your query using the standard MongoDB operators (e.g., $gt, $in).

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

The best way is to run two queries like you did. One to retrieve the _id value and the other to update your documents.

You can't assign y's value to x and new Date().getTime() to y using a single MongoDB query. You need to first retrieve y value using the .findOne() method and then use another query to update the document.

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

Upvotes: 1

Related Questions