Search code examples
mongodbmongodb-queryrefdbref

DBref in MongoDB


I'm trying to make queries with MongoDB but i have a questions.

Query and structure: enter image description here

How do I view information about the author at that job with this query? (for example I want to see the name of the autor with the information of the job)


Solution

  • Mongo does not support joins as in relational databases. You'll need to execute a second query to get the autore data.

    var opera = db.tabella2.findOne();
    
    var autore = db[opera.autore.$ref].find({id:opera.autore.$id});
    

    Read more at http://docs.mongodb.org/manual/reference/database-references/

    EDIT:

    Sometimes you'll want to embed documents to have a better data model. If you have a 1-to-n relation between documents in tabella2 and tabella1, you can have a single tabella collection with documents like this, for example:

    {
      "_id": 1,
      "nome": "Matteo",
      "cognome": "Cappella",
      "opere": [
        {
          "_id": 1,
          "titolo": "Eppoi",
          "categoria": "back-end",
        }
      ]
    }
    

    Read more at http://docs.mongodb.org/manual/core/data-model-design/