Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb Bson type to Json

Tags:

json

c#

mongodb

I am testing my asp.net core 2.2 web api with Postman. I write the JSON manually like this (httppatch):

{
    "query": "{\"name\": \"foo\"}",

    "update": [ "{\"$set\":{\"name\":\"foo2\"}}","{\"$set\":{\"path\": \"foo2 path\"}}" ]
}

Now I am thinking how can I build the patch body on the client side. My question is how can I get the equivalent of this code in json to make it look like the one I write manually?

var query = Builders<T>.Filter.Eq(e => e.name, "foo");
var updates = Builders<T>.Update.Set(e => e.name, "foo2").Set(e => e.Path, "foo2 path");

I guess it's all about serialization, any idea how can I make it?

--Update--

I found this:

var serializerRegistry = BsonSerializer.SerializerRegistry;
var documentSerializer = serializerRegistry.GetSerializer<T>();
var upList = updates.Render(documentSerializer, serializerRegistry);

but it grabs only the last set it combines all sets in one (My bad, thanks to @Simon Mourier to pointing out my mistake !)

like image 297
Sinan Avatar asked Mar 26 '19 15:03

Sinan


People also ask

Can I convert BSON to JSON?

Converting a BSON Object to a JSON StringUse the asString method to convert the BSON document to an extended JSON string. See http://docs.mongodb.org/manual/reference/mongodb-extended-json/ for more information on extended JSON.

Does MongoDB convert JSON to BSON?

Does MongoDB use BSON or JSON? MongoDB stores data in BSON format both internally, and over the network, but that doesn't mean you can't think of MongoDB as a JSON database. Anything you can represent in JSON can be natively stored in MongoDB, and retrieved just as easily in JSON.

What is BSON type in MongoDB?

BSON is a binary serialization format used to store documents and make remote procedure calls in MongoDB. The BSON specification is located at bsonspec.org . Each BSON type has both integer and string identifiers as listed in the following table: Type. Number.

How do I export data from MongoDB to JSON?

mongoexport command is used to export MongoDB Collection data to a CSV or JSON file. By default, the mongoexport command connects to mongod instance running on the localhost port number 27017. Field_name(s) - Name of the Field (or multiple fields separated by comma (,) ) to be exported.


1 Answers

Here's the solution:

On the client side

        // serializer
        var serializerRegistry = BsonSerializer.SerializerRegistry;
        var documentSerializer = serializerRegistry.GetSerializer<T>();

        // filter and update
        var filter = Builders<T>.Filter.Eq(e => e.Level, 2);
        var updates = Builders<T>.Update
                     .Set(e => e.Name, "foo2")
                     .Set(e => e.Path, "foo2 path")
                     .Inc(e => e.Level, 1);

        // get the string of the filter and the update
        var filterString = filter.Render(documentSerializer, serializerRegistry);
        var updateString = updates.Render(documentSerializer, serializerRegistry);

        // instantiate patch object with properties to json
        Patch patch = new Patch()
        {
            Query = filterString.ToJson(),
            Update = updateString.ToJson()
        };

        // patch object to json
        var patchJson = patch.ToJson();

On the server side

    [HttpPatch]
    public async Task<IActionResult> PatchOne([FromBody]Patch patch)
    {
        // don't need to ModelState.isValid, it's done on binding
        
        try
        {
            var update = BsonDocument.Parse(patch.Update);
            var filter = BsonDocument.Parse(patch.Query);

            var result = await _serviceBase.UpdateOneAsync(filter, update);
            
            ...

        }
        catch (System.Exception ex)
        {

            return StatusCode(StatusCodes.Status500InternalServerError, ex.Message.ToJson());
        }
    }

Global Modals (my solution structure)

public class Patch
{
    [Required]
    public string Query { get; set; }
    [Required]
    public string Update { get; set; }
}

Thanks for your help !!

like image 108
Sinan Avatar answered Oct 21 '22 04:10

Sinan