I'm trying to create a new field in all my documents in a collection. That field will be an array with another field's value as (for now) the single value.
This is my code:
var builder = new UpdateDefinitionBuilder<Member>();
var update = builder.AddToSet(f => f.Sids, "$Sid");
var models = new WriteModel<Member>[]
{
new UpdateManyModel<Member>(FilterDefinition<Member>.Empty, update)
};
new MongoClient().GetDatabase("mydb").GetCollection<Member>().BulkWrite(models);
It almost worked: the new field (Sids) was created as an array, but with the literal value $Sid instead of the value from the Sid field.
What am I missing?
great answer by mickl...
starting with mongodb server v4.2 you can refer to existing fields of the documents using aggregation pipeline stages as described here.
in case anybody's interested here's a sample program using MongoDB.Entities doing the same:
using MongoDB.Entities;
using System;
using System.Collections.Generic;
namespace StackOverflow
{
public class Program
{
public class Member : Entity
{
public string Sid { get; set; }
}
private static void Main(string[] args)
{
new DB("test");
var members = new List<Member>();
for (int i = 1; i <= 10; i++)
{
members.Add(new Member
{
Sid = Guid.NewGuid().ToString()
});
}
members.Save();
DB.Update<Member>()
.Match(_ => true)
.WithPipelineStage("{ '$set': { 'Sids': ['$Sid'] } }")
.WithPipelineStage("{ '$unset': ['Sid'] }")
.ExecutePipeline();
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With