forked from mbdavid/LiteDB
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add Upsert to LiteCollection mbdavid#94
- Loading branch information
Showing
1 changed file
with
49 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
using System; | ||
using System.Collections.Generic; | ||
using System.Linq; | ||
|
||
namespace LiteDB | ||
{ | ||
public partial class LiteCollection<T> | ||
{ | ||
/// <summary> | ||
/// Insert or Update a document in this collection. Returns false if not found document in collection | ||
/// </summary> | ||
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); | ||
} | ||
|
||
/// <summary> | ||
/// Insert or Update a document in this collection. Returns false if not found document in collection | ||
/// </summary> | ||
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); | ||
} | ||
|
||
/// <summary> | ||
/// Insert or Update all documents | ||
/// </summary> | ||
public int Upsert(IEnumerable<T> documents) | ||
{ | ||
if (documents == null) throw new ArgumentNullException("document"); | ||
|
||
return _engine.Value.Upsert(_name, documents.Select(x => _mapper.ToDocument(x))); | ||
} | ||
} | ||
} |