Exemple #1
0
        /// <summary>
        /// Adds or replaces a document within the specified collection.
        /// </summary>
        /// <param name="id">The id of the document to add or replace. If null the document will be added with a newly generated id.</param>
        /// <param name="collection">The name of the collection to add or replace the document within.</param>
        /// <param name="document">The document to add or replace. Note: These must be able to be serialized as a BsonDocument.</param>
        /// <returns>The id of the document if it was added or replaced, null otherwise.</returns>
        public string AddOrReplace(string id, string collection, ExpandoObject document)
        {
            if (!string.IsNullOrWhiteSpace(collection) && isCollectionNameValid(collection) && document != null)
            {
                try
                {
                    MongoCollection mongoCollection = database.GetCollection<BsonDocument>(collection);

                    // Create a BsonDocument to save from the ExpandoObject.
                    BsonDocument bsonDocument = document.ToBsonDocument();

                    // Check that the supplied document contains a ID_FIELD_NAME property.
                    if (!bsonDocument.Names.Contains(ID_FIELD_NAME))
                    {
                        if (string.IsNullOrEmpty(id))
                        {
                            // Add an ID_FIELD_NAME property to the document with a newly generated Id.
                            bsonDocument.Add(ID_FIELD_NAME, ObjectId.GenerateNewId());
                        }
                        else
                        {
                            // Add an ID_FIELD_NAME property to the document with the supplied id.
                            bsonDocument.Add(ID_FIELD_NAME, new ObjectId(id));
                        }
                    }

                    // Add or replace the document.
                    WriteConcernResult result = mongoCollection.Save(bsonDocument);
                    if (result.Ok)
                    {
                        // The document was added or replaced.
                        return ((ObjectId)bsonDocument[ID_FIELD_NAME]).ToString();
                    }
                    else
                    {
                        // There was an error adding or replacing the document.
                        return null;
                    }
                }
                catch (Exception)
                {
                    // There was an error adding or replacing the document in the collection.
                    return null;
                }
            }
            else
            {
                // A null id or collection was supplied or the collection name was invalid.
                return null;
            }
        }