Doubt DBRef Mongodb

4

I have two collections in mongodb called companies and users:

********** Coleção Empresas **********

    {
      "_id": ObjectId("54f38340448d3f436993edf6"),
      "cnpj": "12345678900000",
      "razao": "EMPRESA TESTE",
      "status": 0,
      "cidade": "ARACAJU",
      "uf": "SE",
      "usuarios": {
        "$ref": "user",
        "$id": ObjectId("5126bc054aed4daf9e2ab772")
      }
    }

********** Coleção Usuarios **********

{
    "_id" : ObjectId("5126bc054aed4daf9e2ab772"),
    "cnpj" : "12345678900000",
    "usuario" : "USER 01",
    "senha" : "1234",
    "chave" : "12345",
    "status" : 0,
    "codigo" : "120",
    "tipo" : "A"
}

I'm having a hard time getting a find with company data information along with the data of the searched user.

I know there is a reference in the documentation where it would look something like this:

{ "$ref" : <value>, "$id" : <value>, "$db" : <value> }

Below is a projection of how I would need the result:

********* RESULTADO **********

 {
   "_id": ObjectId("54f38340448d3f436993edf6"),
   "cnpj": "12345678900000",
   "razao": "EMPRESA TESTE",
   "status": 0,
   "cidade": "ARACAJU",
   "uf": "SE",
   "usuarios": {
     "_id": ObjectId("5126bc054aed4daf9e2ab772"),
     "cnpj": "12345678900000",
     "usuario": "USER 01",
     "senha": "1234",
     "chave": "12345",
     "status": 0,
     "codigo": "120",
     "tipo": "A"

   }
 }

Thanks in advance to all who can help.

    
asked by anonymous 01.03.2015 / 22:39

1 answer

1

MongoDB is not able to mount this structure natively. The "join" has to be done manually by your application - this logic could be abstracted by a library. That is, basically what you can do is: find the company, extract the user ref and id, and perform a query to retrieve the user, and finally combine the results manually into a single document.

    
29.04.2015 / 02:31