/// <summary> /// Saves strongly typed document to collection. /// <remarks>If document has property of type <see cref="ObjectId"/> and named 'Id' - it will be set after save</remarks> /// </summary> /// <typeparam name="TDocument">Document type</typeparam> /// <param name="document">Document to save</param> /// <param name="merge">If true the merge will be performed with old and new objects. Otherwise old object will be replaced</param> /// <returns>Id of saved document</returns> public unsafe ObjectId Save <TDocument>(TDocument document, bool merge) { using (var stream = Database.StreamPool.GetStream()) using (var writer = new BsonWriter(stream)) { Serializer.Serialize(writer, document); ObjectId objectId; bool saveOk = false; fixed(byte *streamPointer = &stream.GetBuffer()[0]) { saveOk = _functions.SaveBson(CollectionHandle, streamPointer, &objectId, merge); } if (!saveOk) { throw EjdbException.FromDatabase(Database, "Failed to save document"); } IdHelper <TDocument> .SetId(document, ref objectId); return(objectId); } }
/// <summary> /// Loads JSON object identified by OID from the collection. /// </summary> /// <remarks> /// Returns <c>null</c> if object is not found. /// </remarks> /// <param name="id">Id of an object</param> public TDocument Load <TDocument>(ObjectId id) { using (var bson = new BsonHandle(() => _functions.LoadBson(CollectionHandle, ref id), Database.Library)) { //document does not exists if (bson.IsInvalid) { return(default(TDocument)); } using (var stream = Database.Library.ConvertToStream(bson)) using (var reader = new BsonReader(stream)) { var document = Serializer.Deserialize <TDocument>(reader); IdHelper <TDocument> .SetId(document, ref id); return(document); } } }
/// <summary> /// Returns a result with specified index from results /// </summary> public unsafe TDocument this[int index] { get { EnsureInRange(index); int size; var resultPointer = CursorResult(index, out size); using (var stream = new UnsafeStream(resultPointer)) using (var reader = new BsonReader(stream)) { //TODO: Try to move this hack to deserialization step var id = *((ObjectId *)(resultPointer + 9)); TDocument result = Serializer.Deserialize <TDocument>(reader); IdHelper <TDocument> .SetId(result, ref id); return(result); } } }