6

Suppose I have two fields F1 and F2. I want to update F1 to become F1 + ", " + F2. Can I do so with a single update command in mongo?

mark
  • 59,016
  • 79
  • 296
  • 580

2 Answers2

4

No, you can't do that. You can't use expressions in mongodb updates. The only way is to fetch this document to the client, compose new field value there and issue a prepared update statement.

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
  • 4
    (*this got me thinking: why is it so? It shouldn't be too difficult to implement simple field references. No, NO, I shouldn't think about that, I've got work to do.*) – Sergio Tulentsev Apr 19 '12 at 12:06
2

As it was mentioned by Sergio, you can not do this even a year after the question was asked with version 2.4.8. But if you need to do this, you can use this

db.yourCollection.find({}).forEach(function(doc) {
  doc.F1 = doc.F1 + ", " + doc.F2;
  delete doc.F2;
  db.yourCollection.save(doc);
});
Salvador Dali
  • 214,103
  • 147
  • 703
  • 753
  • Actually, I hit other walls with MongoDB, more serious than that. At the end, I have taken a painful decision to migrate my back end from MongoDB to PostgreSQL. – mark Nov 08 '13 at 12:12
  • Can you describe your problems? It might be useful for others to learn from your mistakes :-) – Salvador Dali Nov 08 '13 at 13:20
  • 1
    **Non-counting B-Trees.** I need to produce reports with counts of records satisfying various criteria. It is a showstopper. **Unique optional fields** I have some fields which are unique if not null, but there may be many records with null values there. The way mongo indexes such fields makes it impossible to look for records with the null value there - you have to use surrogate non null values, which is a real pain to maintain. **Wild on the memory** MongoDB is a truely server oriented, it does not tolerate any other application running along, because by its very design it takes all the RAM. – mark Nov 08 '13 at 15:12
  • http://stackoverflow.com/questions/12437790/when-to-use-couchdb-over-mongodb-and-vice-versa/14677861#14677861 – mark Nov 08 '13 at 15:13
  • @mark wow, thank you very much for information. This is definitely worse knowing. – Salvador Dali Nov 08 '13 at 20:54