sql >> Base de Datos >  >> NoSQL >> MongoDB

Actualización de Mongo dentro de una matriz anidada doble

Ahora hay (MongoDB>=3.6) una manera de hacer esto con arrayFilters y $[identifier] .

El siguiente ejemplo usa mangosta y agregará un elemento a una matriz dentro de una matriz anidada doble. Un buen artículo que explica esto está aquí .

  const blogPost = await BlogPost.create({
    title    : 'A Node.js Perspective on MongoDB 3.6: Array Filters',
    comments : [
      { author : 'Foo', text : 'This is awesome!', replies : { name : 'George', seenBy : ['Pacey'] } },
      { author : 'Bar', text : 'Where are the upgrade docs?', replies : { name : 'John', seenBy : ['Jenny'] } }
    ]
  });

  const updatedPost = await BlogPost.findOneAndUpdate({ _id : blogPost._id }, {
    $addToSet : {
      'comments.$[comment].replies.$[reply].seenBy' : 'Jenny'
    }
  }, {
    arrayFilters : [{ 'comment.author' : 'Foo' }, { 'reply.name' : 'George' }],
    new          : true
  });

  console.log(updatedPost.comments[0].replies);