[mongodb-csharp] How to insert a JSON document as a string

3,275 views
Skip to first unread message

sukchr

unread,
May 17, 2010, 4:10:11 PM5/17/10
to mongodb-csharp
I've just started playing with mongodb. I'm using the Json.NET (http://
json.codeplex.com/) library to generate a JSON document. Is it
possible to persist a JSON document as a string to mongodb using the
mongodb-csharp driver?

I want to do this:
var json = @"{""name"": ""value""}";
mongo["test"]["test"].Insert(json);

craiggwilson

unread,
May 17, 2010, 4:54:12 PM5/17/10
to mongodb-csharp
This is an open ticket item at http://jira.mongodb.org/browse/CSHARP-29.
Vote for it if you find it worthwhile.

On another point, can you describe your reason for doing this? Most
of the time, you should have different entity objects than your data
objects. As in, entities should be more than just data holders.
Hence, load up your entity and then create a data object to send to
your presentation tier (or across the wire).

In addition, if the reasoning is to support a more strongly typed
entity model, then that is coming in the typedcollections branch. I
encourage you to check it out at http://github.com/lanwin/mongodb-csharp/tree/typedcollections.

sukchr

unread,
May 18, 2010, 3:14:11 AM5/18/10
to mongodb-csharp
The reason is that I am using Json.NET to generate the JSON document -
I don't have a class that represents my data. Specifically, I am
developing an application that allows you to define forms like this:

//declare fields
TextBox firstname, lastname;

//create form
var formbuilder = new FormBuilder();
formbuilder.Form("Form")
.Page("Person")
.Field("firstname", out firstname)
.Field("lastname", out lastname);

//populate form with values
var model = new Model()
.SetValue(firstname, "Tom")
.SetValue(lastname, "Sawyer");

//get JSON representation - the structure of the form as well as the
contents of the model determines the generated JSON - uses Json.NET to
create the document
string json = formbuilder.ToJson(model);

//produces string:
{
"Form": {
"Person": {
"Firstname": "Tom",
"Lastname": "Sawyer"
}
}
}


Steve Wagner

unread,
May 18, 2010, 5:13:06 AM5/18/10
to mongodb...@googlegroups.com
I think it would be much easier for you if you create an object model like

class Person{
public string Firstname{get;set;}
public string Lastname{get;set;}
}

Json.Net can create parse Json and create an object from it and back.
And also MongoDB-CSharp typedcollections can load and save objects directly.

This could work like this:

var person = (Person)JsonConvert.ToObject(json);

person.Firstname = "Bill";

mongo.GetDatabase("Test").GetCollection<Person>().Insert(person);

-Steve

sukchr

unread,
May 18, 2010, 5:36:43 AM5/18/10
to mongodb-csharp
I understand what you're saying. The only problem is that my forms
aren't known at compile-time. They are created dynamically at run-time.

Dody Gunawinata

unread,
May 18, 2010, 5:42:08 AM5/18/10
to mongodb...@googlegroups.com
If you are on C# 4,  try expando objects so you can assign any properties as needed and serialize them to json using JSON.Net.

And using the following code, you will also be able to convert a JSON object to a dynamic object in C#

public static class DynamicUtils
    {
        public static object ConvertJTokenToObject(JToken token)
        {
            if (token is JValue)
            {
                return ((JValue)token).Value;
            }
            if (token is JObject)
            {
                ExpandoObject expando = new ExpandoObject();
                (from childToken in ((JToken)token) where childToken is JProperty select childToken as JProperty).ToList().ForEach(property =>
                {
                    ((IDictionary<string, object>)expando).Add(property.Name, ConvertJTokenToObject(property.Value));
                });
                return expando;
            }
            if (token is JArray)
            {
                object[] array = new object[((JArray)token).Count];
                int index = 0;
                foreach (JToken arrayItem in ((JArray)token))
                {
                    array[index] = ConvertJTokenToObject(arrayItem);
                    index++;
                }
                return array;
            }
            throw new ArgumentException(string.Format("Unknown token type '{0}'", token.GetType()), "token");
        }
    }

Usage sample:

var parsed = JObject.Parse(response.Content);
dynamic result = DynamicUtils.ConvertJTokenToObject(parsed);



On Tue, May 18, 2010 at 12:36 PM, sukchr <suk...@gmail.com> wrote:
I understand what you're saying. The only problem is that my forms
aren't known at compile-time. They are created dynamically at run-time.



Message has been deleted
Message has been deleted

Steve Wagner

unread,
May 18, 2010, 8:37:10 AM5/18/10
to mongodb...@googlegroups.com
Something like this should work.

var exists = _collection.FindOne(new Document("_id",new
MongoRegex("Mooo"))!=null;

On 18.05.2010 14:30, Rei wrote:
> Hello all,
>
> Its probably something really dumb, but, I can't for the life of me,
> write a query to test for the following condition.
>
> given a collection of say
>
> { _id : "Mooo" }, { _id : "Mooo1" }, { _id : "Mooo2" }
>
> (Yes, very creative example I know :P )
>
> How would you go about creating a query for retrieving _id : "Mooo" in
> a
> case insensitive way.
> I'm using a string _id for user names, and I'd like to perform the
> search before hand to avoid the creation of :
>
> Mooo, mooo, mOOO and so on so forth.
>
> Sorry about my English, not had enough coffee yet.
>
> /Rei

Rei Roldán

unread,
May 18, 2010, 8:46:12 AM5/18/10
to mongodb...@googlegroups.com
This works, but is case sensitive :(

Rei

unread,
May 18, 2010, 8:50:15 AM5/18/10
to mongodb-csharp
new MongoRegex("Mooo", "i")

Makes it insensitive, but also matches Mooooo, MoooMore, MoooHarder :S

Steve Wagner

unread,
May 18, 2010, 11:05:33 AM5/18/10
to mongodb...@googlegroups.com
Yep you should read more about how Regex's in general are working. Then
you could search for specific things.

Rei Roldán

unread,
May 18, 2010, 11:13:55 AM5/18/10
to mongodb...@googlegroups.com
Yeap, seriously will have to grab a Regex book asap! :(
Reply all
Reply to author
Forward
0 new messages