Update MongoDB collection using $toLower

后端 未结 6 1091
盖世英雄少女心
盖世英雄少女心 2020-12-01 05:34

I have an existing MongoDB collection containing user names. The user names contain both lower case and upper case letters.

I want to update all the user names so th

6条回答
  •  旧巷少年郎
    2020-12-01 05:42

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

    // { username: "Hello World" }
    db.collection.update(
      {},
      [{ $set: { username: { $toLower: "$username" } } }],
      { multi: true }
    )
    // { username: "hello world" }
    
    • The first part {} is the match query, filtering which documents to update (in this case all documents).

    • The second part [{ $set: { username: { $toLower: "$username" } } }], is the update aggregation pipeline (note the squared brackets signifying the use of an aggregation pipeline):

      • $set is a new aggregation operator which in this case modifies the value for "username".
      • Using $toLower, we modify the value of "username" by its lowercase version.
    • Don't forget { multi: true }, otherwise only the first matching document will be updated.

提交回复
热议问题