I need to create new fields to all existing documents to store the lowercase value of emailAddress(which is an existing field).
await _mongoHelper.MongoDatabase.GetCollection<T>("users").UpdateOneAsync(
(Builders<T>.Filter.Eq("userId", userId)),Builders<T>.Update.Set("fieldInLower", new BsonDocument(new BsonElement("toLower", "$firstName")))).ConfigureAwait(false);
)
Result is :
"fieldInLower" : {
"toLower" : "$firstName"
}
starting from mongodb server v4.2 you can use aggregation pipeline stages to refer to the existing fields as described here .
the following example c# code does the same using 'MongoDB.Entities' which is a more convenient way compared to official driver.
using MongoDB.Entities;
namespace StackOverflow
{
public class Program
{
public class User : Entity
{
public string Email { get; set; }
}
private static void Main(string[] args)
{
new DB("test");
var user = new User { Email = "Email@Domain.Com" };
user.Save();
DB.Update<User>()
.Match(u => u.ID == user.ID)
.WithPipelineStage("{ $set: { LowerCaseEmail: { $toLower: '$Email' } } }")
.WithPipelineStage("{ $unset: 'Email'}") //if you need to remove the original field
.ExecutePipeline();
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.