d--b
d--b

Reputation: 5779

MongoDB collection to .Net dictionary best practice

I have an application that performs fast operations on in-memory data. This data is represented in memory as a Dictionary<MyKey,MyData>. The MyKey is a class that contains a few string tags:

public class MyKey
{
    string tag1;
    string tag2;
    ... 
}

and MyData is an object that contains some texts.

I would like to store it in MongoDB as a collection of documents like:

{
    tag1: "foo1",
    tag2: "foo2",
    mydata: { ... }
},
{
    tag1: "bar1",
    tag2: "bar2",
    mydata: { ... }
}...

so that I can use mongodb selectors:

db.MyCollection.find({tag1: "foo1"})

But then it becomes really annoying to write the serializer / deserializer, since a one-to-one mapping would do:

{
    mykey: { tag1: "foo1", tag2: "foo2"},
    mydata: { ... }
}

I feel like this is a pretty common issue. What is the best solution to achieve this? I want to keep the original Dictionary structure but I don't want to reinvent the wheel for the Serializer.

Any idea / tutorial I could follow? Is this even something I should be doing?

Upvotes: 0

Views: 765

Answers (1)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230336

There's no issue with document of this form:

{
    mykey: { tag1: "foo1", tag2: "foo2"},
    mydata: { ... }
}

You can still query it.

db.collection.find({'mykey.tag1': 'foo1'})

Does this answer your question? Is there another particular reason for wanting that document structure?

Upvotes: 2

Related Questions