MongoDB update. Trying to set one field from a property of another

前端 未结 4 1675
误落风尘
误落风尘 2021-02-05 20:08

What I\'m trying to do is pretty straightforward, but I can\'t find out how to give one field the value of another.

I simply want to update one field with the character

相关标签:
4条回答
  • 2021-02-05 20:31
    1. Your are using exists in the wrong way.
      Syntax: { field: { $exists: <boolean> } }

    2. You use of $where is also incorrect
      Use the $where operator to pass either a string containing a JavaScript expression or a full JavaScript function to the query system

      db.myCollection.find( { $where: "this.credits == this.debits" } ); db.myCollection.find( { $where: "obj.credits == obj.debits" } );

      db.myCollection.find( { $where: function() { return (this.credits == this.debits) } } );

      db.myCollection.find( { $where: function() { return obj.credits == obj.debits; } } );

    I think you should use Map-Reduce for what you are trying to do.

    0 讨论(0)
  • 2021-02-05 20:35

    As far I know the easiest way is the read and write aproach:

    //At first, get/prepare your new value:
    var d= db.yourColl.fetchOne({....});
    d.field1== d.field2.length;
    
    // then update with your new value
    db.yourColl.save(d);
    
    0 讨论(0)
  • 2021-02-05 20:45

    Try the following code:

    db.collection.find(your_querry).forEach(function(doc) {
      doc.field1 = doc.field2.length;
      db.collection.save(doc);
    });
    

    You can use your_querry to select only part of the original collection do perform an update. If you want to process an entire collection, use your_querry = {}.

    If you want all operations to be atomic, use update instead of save:

    db.collection.find( your_querry, { field2: 1 } ).forEach(function(doc) {
      db.collection.update({ _id: doc._id },{ $set: { field1: doc.field2.length } } );
    });
    
    0 讨论(0)
  • 2021-02-05 20:53

    Starting Mongo 4.2, db.collection.update() can accept an aggregation pipeline, finally allowing the update/creation of a field based on another field:

    // { "_id" : ObjectId("5e84c..."), "field1" : 12, "field2" : "world" }
    db.collection.update(
      { "_id" : ObjectId("5e84c...") },
      [{ $set: { field1: { $strLenCP: "$field2" } } }]
    )
    // { "_id" : ObjectId("5e84c..."), "field1" : 5, "field2" : "world" }
    
    • The first part {} is the match query, filtering which documents to update.

    • The second part [{ $set: { field1: { $strLenCP: "$field2" } } }] is the update aggregation pipeline (note the squared brackets signifying the use of an aggregation pipeline). $set is a new aggregation operator and an alias for $addFields. Any aggregation operator can be used within the $set stage; in our case $strLenCP which provides the length of field2.

    0 讨论(0)
提交回复
热议问题