Skip to content

Commit

Permalink
Add Upsert to LiteCollection mbdavid#94
Browse files Browse the repository at this point in the history
  • Loading branch information
mbdavid committed Nov 22, 2016
1 parent eef5f8e commit 8660cf0
Showing 1 changed file with 49 additions and 0 deletions.
49 changes: 49 additions & 0 deletions Database/Collections/Upsert.cs
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)));
}
}
}

0 comments on commit 8660cf0

Please sign in to comment.