RobThree / MongoRepository

Repository abstraction layer on top of Official MongoDB C# driver
https://www.nuget.org/packages/MongoRepository/
MIT License
307 stars 141 forks source link

Mongo update array element (.NET driver 2.0) #32

Closed mattcahill01 closed 8 years ago

mattcahill01 commented 8 years ago

Hello,

How best i use MongoRepository in order to update an element within an Array within a Document? e.g., trying to emulate this code http://stackoverflow.com/questions/31453681/mongo-update-array-element-net-driver-2-0

but the repo doesn't accept this: var result = this._userRepository.Update(filter, update);

Any advice appreciated. thank you,

mattcahill01 commented 8 years ago

Hi Guys (Rob :) ), Any chance of some feedback?

RobThree commented 8 years ago

MongoRepository is based on entire documents (entities) to be updated; simply pull the entity from Mongo, make your changes to the entity/document, and Update to save again.

If I misunderstood your question, then please post code to reproduce / demonstrate your problem.

mattcahill01 commented 8 years ago

I have ended up just adding this new method to the repo

///

    /// Upserts an entity.
    /// </summary>

    /// <param name="filter">The filter.</param>
    /// <param name="updateDefinition">The update definition.</param>
    public virtual void Update(FilterDefinition<T> filter, UpdateDefinition<T> updateDefinition)
    {
      var result = this.collection.UpdateOne(filter, updateDefinition);  
    }
RobThree commented 8 years ago

...which is fine (for you / your project) but not for MongoRepository. The Update method you show above leaks mongo-specific stuff like FilterDefinition and UpdateDefinition. MongoRepository aims to stay as persistance-agnostic as possible so you could, in theory, easily swap it out for another persistance layer (as long as it implements the repository interface). MongoRepository's goal is to "narrow" the usage of the Mongo API, not enhance it. It aims to provide only the most basic operations (Get/Update/Delete/...) and no more so you won't be easily enticed to use mongo-specific stuff that later will be hard to change to another persistance layer. If you don't want that or don't need that you'd probably better use the mongo-csharp-driver directly.

Having said that: I would've probably implemented your method as an extension method.

mattcahill01 commented 8 years ago

Ah Right. Makes sense if that is the goal. I like to have a bit of both however - the nice abstracted repo but some Mongo specific goodies as well.

RobThree commented 8 years ago

I understand; sometimes it's nice to have your cake and eat it too :wink: But consider using an extension method so you can easily 'upgrade' to a newer version of MongoRepository should it ever change/update.