I cannot seem to find a way to insert element at specific index in an array in the Mongodb C# Driver. - For example insert an element at position 0.
The only obvious insert into the array is using the push but that is appending to the end of the array.
I have tried the following but does not work.
var filter = Builders<ChatRoom>.Filter.Eq(Keys.MongoId, ObjectId.Parse(chatRoomId));
var update = Builders<ChatRoom>.Update.Set(Keys.Comments + ".$.-1", comment);
or
var update = Builders<ChatRoom>.Update.Push(Keys.Comments+".-1",comment);
But it doesn't work. Also I cannot seem to find the $position operator in the Mongodb C# docs. - was hoping that could help, if it was relevant.
Okay super easy, after exploring around the driver and the help of intellisense from Visual Studio here is the correct answer:
var filter = Builders<ChatRoom>.Filter.Eq(Keys.MongoId, ObjectId.Parse(chatRoomId));
var update = Builders<ChatRoom>.Update.PushEach(Keys.Comments, new List<Comment>() { comment }, position: 0);
await MongoCollections.GetChatRoomCollection().UpdateOneAsync(filter, update);