3

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.

1 Answer 1

4

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);
Sign up to request clarification or add additional context in comments.

3 Comments

Sometimes, it's best to try and figure out how mongodb supports this before attempting it in the driver: docs.mongodb.org/manual/reference/operator/update/push
@CraigWilson Thanks for your comment, you must be the guy who created the Driver, nice to meet you. Yes I agree, I actually knew mongodb supports it as i have written it once in Python. I just didn't know how it was done in C#.
@CraigWilson Sorry, but what is the time complexity of this operation? I assume O(n) but I'd like clarification if you please

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.