Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

182
Views
Actualice el último elemento de una matriz anidada en mongodb

He intentado la siguiente consulta de mongoose que no parece funcionar:

 Model.findOneAndUpdate( { name: origin }, { $set: { 'field1.$[id1].field2.-1': "value" } }, { arrayFilters: [ { 'id1.userId': "customerId" } ], new: true } );

Nota: field1 y field2 son matrices

MongoDB no acepta los índices negativos, lo que está causando problemas.

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Puede considerar usar el operador $set (agregación) y usar el operador double $map :

 db.collection.aggregate([ { $match: { name: "myname" } } { $set: { field1: { $map: { input: "$field1", in: { $cond: { if: { $ne: [ "$$this.userId", "customerId" ] }, then: "$$this", else: { $mergeObjects: [ "$$this", { field2: { $concatArrays: [ { $slice: [ "$$this.field2", { $add: [ { $size: "$$this.field2" }, -1 ] } ] }, ["value"] ] } } ] } } } } } } } ])

Parque infantil Mongo

over 4 years ago · Santiago Trujillo Report

0

Aplique el operador $set junto con el operador posicional $ en su actualización para cambiar el campo de nombre.

El operador posicional $ identificará el elemento correcto en la matriz para actualizar sin especificar explícitamente la posición del elemento en la matriz, por lo que su declaración de actualización final debería verse así:

 db.collection.update( { "friends.u.username": "michael" }, { "$set": { "friends.$.u.name": "hello" } } )

Respuesta tomada de - https://stackoverflow.com/a/34431571

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!