You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesi贸n a prueba de IA

Antes: $249

Currency
$209
Suscr铆bete

Termina en:

1 D铆as
1 Hrs
28 Min
56 Seg

Referencias circulares o bidireccionales

18/22
Resources

How to handle many-to-many relationships with self-referenced references?

Many-to-many relationships are essential for modeling complex database systems, but they can also be challenging. In this session, we explore how to create a many-to-many relationship between stores and products, allowing both elements to cross-reference.

How do we update a product to include references to stores?

To have a relationship that allows us to know in which stores a specific product is found, we must first update the product with the corresponding store IDs. To do this, we can follow these steps:

  1. Identify the product and the store:

    • Perform a query to get the ID of the product you want to update.
    • Perform another query to identify which store you want to link to the product.
  2. Perform the update in the database:

    • Create a new script to perform an Update instead of an Insert.
    • Specify the database and perform an updateOne on the product in question.
    db.products.updateOne( { _id: ObjectId("product_id") }, { $set: { StoreIDs: ["store_id"] } } })

When running the script, the database will update the product document by adding a StoreIDs field, which will contain a list of the associated stores.

How do we check references between products and stores?

Once the product has been updated, it is crucial to verify that the relationships are correctly implemented:

  1. Query the product to verify the references:

    • Performs a query to check if the product has the StoreIDs field with the IDs of the associated stores.
    db.products.findOne( { _id: ObjectId("product_id") })
  2. Ensure that the relationships can be queried from both directions:

    • Ensure that Stores can also be related to products.
    • Allow relationships to be resolved from the Stores collection as well as from the Products collection.
    db.products.aggregate([ { $lookup: { from: "stores", localField: "StoreIDs", foreignField: "_id", as: "DetailStores" } }])

When should you use self-referencing?

Self-references are useful when information needs to be accessed from either side of the relationship. It is key to decide if the information should be referenced from both sides or only from one based on user experience or business needs.

  • Bidirectional references: These are recommended when the information is consumed frequently and jointly from different points of the application (for example, a conference system where it is necessary to know both the sessions of a speaker and the speakers of a session).

  • Unilateral references: These are sufficient when most of the queries or actions are focused on one side of the relationship.

Adopting the right strategy to implement self-references in databases contributes significantly to the efficiency of the application and avoids unnecessary redundancies.

Contributions 1

Questions 1

Sort by:

Want to see more contributions, questions and answers from the community?

Referencias circulares o bidireccionales

Es parte del N-N. Donde cada coleccion tiene documentos que apuntan a todos los relacionados de otra coleccion (O en la misma).

Casos de uso

  • Usa refencia cuando la relacion es n-n
  • Cuando la informaci贸n es consultada en conjunto. Por si necesitamos las referencias que tiene algun documento sin importal cual sea. Para resolver m谩s facil relaciones y rapido.

Ejemplo

Parte 2.

Ahora trabajemos en la otra referencia.

Facilitar la busqueda de ID

para el proximo proceso

db.products.aggregate([
  { 
    $lookup: { // buscar las id que necesitamos
      from: 'stores',
      localField: '_id',
      foreignField: 'products_ids',
      as: 'stores'
    }
  },
  {
    $project: { // filtrar para ver mejor las id
      _id: 1, // id producto
      stores: { // en tiendas
        _id: 1 // id tienda
      }
    }
  }
])

Modificar Productos

// prod 1
db.products.updateOne(
    {_id: ObjectId('649923c970dfee1c60f23f54')},
    {
        $set: {
            stores_ids: [
                ObjectId("649923f457514437ac501dd4")
            ]
        }
    }
)

// prod 2
db.products.updateOne(
    {_id: ObjectId('649923c970dfee1c60f23f55')},
    {
        $set: {
            stores_ids: [
                ObjectId("649923f457514437ac501dd4"),
                ObjectId("649923f457514437ac501dd5"),
            ]
        }
    }
)

//prod 3
db.products.updateOne(
    {_id: ObjectId('649923c970dfee1c60f23f56')},
    {
        $set: {
            stores_ids: [
                ObjectId("649923f457514437ac501dd5")
            ]
        }
    }
)

Ver las tiendas en el producto

use("platzi_store")
db.products.find()

db.products.aggregate([
  { 
    $lookup: { // buscar las id que necesitamos
      from: 'stores',
      localField: 'stores_ids',
      foreignField: '_id',
      as: 'stores'
    }
  }
])