This is a matter of document design. Roughly, there are two routes to follow:
- include the subdocument (
artigo
) within the root document (usuario
)
- link/reference the secondary document (
artigo
) in primary school (usuario
)
Since you seem to need an identifier for each article, I would suggest first trying to find a natural identifier, like an existing unique archive number. If this is not possible, you can generate any unique identifier at the time of saving the article for the first time, like a UUID/GUID or some string derived from the title and possibly publication date (e.g.: id_artigo: "2014_08_03_lorem_imsum"
).
If you prefer a sequential number for these articles, one simple way to achieve this is by creating an auxiliary Collection sequencias
that you can use to generate these numbers. I use this technique quite a lot with findAndModify()
:
var contador = db.sequencias.findAndModify({
query: {'_id': 'artigos'},
fields: {'_id': 0, 'seq': 1},
update: {'$inc': {'seq': 1}},
new: true,
upsert: true
});
var novo_num = contador.seq;
The alternative 1 applies well when articles have only one author/user, as you will not duplicate anything:
{
_id: ObjectId("123456..."),
user: "João",
artigos:[
{
id_artigo: "2014_08_03_lorem_impsum",
data: new Date(2014, 07, 03),
titulo: "Lorem ispsum.",
texto: "Lorem ipsum dolor sit amet..."
},
{
id_artigo: "2013_12_01_so_um_teste",
data: new Date(2013, 11, 01),
titulo: "Só um Teste",
texto: "Meu primeiro artigo..."
}
]
}
Already the alternative 2 can be used when there is the possibility of the same article being related to more than one author/user, avoiding much duplication of data:
Articles:
{
_id: "2014_08_03_lorem_impsum",
data: new Date(2014, 07, 03),
titulo: "Lorem ispsum.",
texto: "Lorem ipsum dolor sit amet..."
}
{
_id: "2013_12_01_so_um_teste",
data: new Date(2013, 11, 01),
titulo: "Só um Teste",
texto: "Meu primeiro artigo..."
}
Users:
{
_id: ObjectId("123456..."),
user: "João",
artigos: ["2013_12_01_so_um_teste", "2014_08_03_lorem_impsum"]
}
{
_id: ObjectId("987654..."),
user: "Armando",
artigos: ["2014_08_03_lorem_impsum"]
}
We’re talking about subdocuments, right?
– Leonel Sanches da Silva
@Gypsy.
– Kazzkiq