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

184
Views
¿Cómo realizo dos operaciones en el mismo elemento de matriz?

Tengo una colección de users de MongoDB con la estructura de documento (simplificada):

 { _id: ObjectId, name: 'John Doe', sportsList: [ // array of objects { name: 'football', level: 1500, levelHistory: [ // array of objects { from: 1450, to: 1500, date: Date }, ... ] }, { name: 'tennis', level: 1400, levelHistory: [ // array of objects { from: 1350, to: 1400, date: Date }, ... ] }, ] }

Quiero actualizar el elemento de sportsList que tiene el name === 'tennis' así:

  • empujar un nuevo elemento en levelHistory
  • actualice el level Hasta ahora he logrado insertar un nuevo elemento en levelHistory con esta consulta:
 await User.updateOne( { _id: userId, sportsList: { $elemMatch: { name: 'tennis' } } }, { $push: { 'sportsList.$.levelHistory': { date: Date, from: 1400, to: 1450 } }, // how do I set 'level: 1450' in the same query? // if I tried to use a $set: { 'sportsList.$.level': 1450 } mongoDB throws an error } )
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Consulta

  • la actualización de canalización requiere MongoDB >= 4.2
  • mapa en la matriz
  • si el nombre no es tennis no cambies el elemento
  • de lo contrario, combine el elemento (documento incrustado) con un documento que tenga el nuevo nivel y el nuevo levelHistory (la combinación del antiguo con el nuevo elemento)

JugarMongo

 update( {"_id": 1}, [{"$set": {"sportsList": {"$map": {"input": "$sportsList", "in": {"$cond": [{"$ne": ["$$this.name", "tennis"]}, "$$this", {"$mergeObjects": ["$$this", {"level": 1450, "levelHistory": {"$concatArrays": ["$$this.levelHistory", [{"from": 1400, "to": 1450, "date": 4}]]}}]}]}}}}}])
about 4 years ago · Juan Pablo Isaza 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!