Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store metadata describing documents in a MongoDB collection?

What is the best way to store metadata that describe a collection in MongoDB?

I have a collection with an arbitrary and changing number of documents within. As I create new documents, I want to assign a new, temporary name (String) based on the number of documents currently in the collection, e.g. "Doc 1", "Doc 2", ... Since documents could be removed, just doing a count() will not yield a useful result.

One option is to store metadata describing a collection within a different collection, but this seems awkward.

Since Mongo is schema-free, I could keep the collection's metadata within the collection itself, perhaps within a document with the name "metadata". In that case, how would I access that document quickly? Would I need to build an index for "metadata" to get at it immediately, without O(n) search time?

Is there a more standard, or simpler, way than what I described in the previous paragraph? I may end up with more metadata in the future than just a count.

like image 785
ericsoco Avatar asked Nov 02 '12 21:11

ericsoco


1 Answers

You can check this link https://docs.mongodb.com/v3.0/tutorial/create-an-auto-incrementing-field/.

According to the link above, my opinion is that just storing those in a colleciton named metadata with the format:

{
    '_id':'collection1'
    'c': 0,
    'other metadata1': 'foo',
    'other metadata2': 'bar'
}

Then you can get those metadata according to the collection name. If you want to add a field to this document, just use $set with update.

like image 80
Chien-Wei Huang Avatar answered Sep 18 '22 13:09

Chien-Wei Huang