15

私がやろうとしていることは非常に簡単ですが、あるフィールドに別のフィールドの値を与える方法を見つけることができません。

あるフィールドを別のフィールドの文字数で更新したいだけです。

db.collection.update({$exists:true},{$set : {field1 : field2.length}})

ドット表記をしてみました

db.collection.update({$exits:true},{$set : {field1: "this.field2.length"}})

javascript構文を使用するだけでなく

db.collection.update({$exits:true},
                     {$set : {field1: {$where : "this.field2.length"}})

しかし、文字列をコピーして、それぞれ「notOkforstorage」を取得しました。何か助けはありますか?

更新:IDでクエリを実行すると、「notOkforStorage」のみが表示されます。

db.collection.update({_id:ObjectID("38289842bbb")},
                     {$set : {field1: {$where :"this.field2.length"}}})
4

4 に答える 4

26

次のコードを試してください。

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

your_querry元のコレクションの一部のみを選択して更新を実行するために使用できます。コレクション全体を処理する場合は、を使用しますyour_querry = {}

すべての操作をアトミックにする場合は、次updateの代わりに使用しsaveます。

db.collection.find( your_querry, { field2: 1 } ).forEach(function(doc) {
  db.collection.update({ _id: doc._id },{ $set: { field1: doc.field2.length } } );
});
于 2012-12-23T09:41:25.830 に答える
10

を開始するMongo 4.2と、db.collection.update()集約パイプラインを受け入れることができ、最終的に別のフィールドに基づくフィールドの更新/作成が可能になります。

// { "_id" : ObjectId("5e84c..."), "field1" : 12, "field2" : "world" }
db.collection.update(
  { "_id" : ObjectId("5e84c...") },
  [{ $set: { field1: { $strLenCP: "$field2" } } }]
)
// { "_id" : ObjectId("5e84c..."), "field1" : 5, "field2" : "world" }
  • 最初の部分{}は一致クエリで、更新するドキュメントをフィルタリングします。

  • 2番目の部分[{ $set: { field1: { $strLenCP: "$field2" } } }]は、更新アグリゲーションパイプラインです(アグリゲーションパイプラインの使用を示す角かっこに注意してください)。$setは新しい集計演算子であり、のエイリアスです$addFields$setステージ内では任意の集計演算子を使用できます。私たちの場合$strLenCP、の長さを提供しますfield2

于 2020-04-01T16:45:26.080 に答える
0

私が知る限り、最も簡単な方法は読み取りと書き込みのアプローチです。

//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);
于 2012-12-23T09:46:44.387 に答える
-1
  1. あなたはexists間違った方法で使用しています。
    Syntax: { field: { $exists: <boolean> } }

  2. $whereの使用も正しくありません
    $where演算子を使用して、JavaScript式を含む文字列または完全なJavaScript関数をクエリシステムに渡します

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

やろうとしていることにMap-Reduceを使うべきだと思います。

于 2012-12-23T08:55:03.063 に答える