From 8660cf0e7f71094295a2afeb1eb700722dab9c3d Mon Sep 17 00:00:00 2001 From: mbdavid Date: Tue, 22 Nov 2016 08:04:12 -0200 Subject: [PATCH] Add Upsert to LiteCollection #94 --- Database/Collections/Upsert.cs | 49 ++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 Database/Collections/Upsert.cs diff --git a/Database/Collections/Upsert.cs b/Database/Collections/Upsert.cs new file mode 100644 index 000000000..a3973c3bd --- /dev/null +++ b/Database/Collections/Upsert.cs @@ -0,0 +1,49 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace LiteDB +{ + public partial class LiteCollection + { + /// + /// Insert or Update a document in this collection. Returns false if not found document in collection + /// + public bool Upsert(T document) + { + if (document == null) throw new ArgumentNullException("document"); + + // get BsonDocument from object + var doc = _mapper.ToDocument(document); + + return _engine.Value.Upsert(_name, doc); + } + + /// + /// Insert or Update a document in this collection. Returns false if not found document in collection + /// + public bool Upsert(BsonValue id, T document) + { + if (document == null) throw new ArgumentNullException("document"); + if (id == null || id.IsNull) throw new ArgumentNullException("id"); + + // get BsonDocument from object + var doc = _mapper.ToDocument(document); + + // set document _id using id parameter + doc["_id"] = id; + + return _engine.Value.Upsert(_name, doc); + } + + /// + /// Insert or Update all documents + /// + public int Upsert(IEnumerable documents) + { + if (documents == null) throw new ArgumentNullException("document"); + + return _engine.Value.Upsert(_name, documents.Select(x => _mapper.ToDocument(x))); + } + } +} \ No newline at end of file