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

351
Views
MongoDB: cómo usar $ proyecto con $ cond en canalización agregada

mi colección tiene una estructura como esta:

 "listQuestion": [ { "answer_type": 0, "listShortAnswer": [], "listQuestionChildren": [], "quiz_type": 1, "listPairing": [], "listAnswer": [ { "is_true": false, "answer_content": " \\[x=-2\\] ", "answer_url_image": "", "answer_url_mp3": "", "answer_id": 136948 }, { "is_true": true, "answer_content": " \\[x=-1\\] ", "answer_url_image": "", "answer_url_mp3": "", "answer_id": 136950 },

Tengo una variable de agregación llamada $$isShowAnswer , si es true , se mostrará is_true , o de lo contrario no lo hará.

aquí está mi proyección con $cond

 $project: { 'listAnswer.is_true': { $cond: { if: { $eq: ["$$isShowAnswer", false] }, then: "$$REMOVE", else: 1} }, },

pero el resultado es como el siguiente

 { "answer_content": " \\[x=-2\\] ", "answer_url_image": "", "answer_url_mp3": "", "answer_id": 136948, "is_true": 1 }, { "answer_content": " \\[x=-1\\] ", "answer_url_image": "", "answer_url_mp3": "", "answer_id": 136950, "is_true": 1 },

¿Cómo puedo eliminar el campo "is_true" si la condición es correcta y no hacer nada si es incorrecta?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Para actualizar una matriz, debe usar $map . Eliminar una clave por condición no es simple, puede usar una solución alternativa con $objectToArray y luego revertir nuevamente con $arrayToObject

 db.getCollection("collection").aggregate([ { $project: { listAnswer: { $map: { input: "$listAnswer", as: 'answer', in: { $cond: { if: { $eq: ["$$isShowAnswer", false] }, then: { $mergeObjects: ["$$answer", { is_true: 1 }] }, else: { $arrayToObject: { $filter: { input: { $objectToArray: "$$answer" }, as: 'item', cond: { $ne: ["$$item.k", 'is_true'] } } } } } } } } } } ])

Otra solución sería

  1. {$unwind: "$listAnswer"}
  2. luego su { $cond: { if: { $eq: ["$$isShowAnswer", false] }, then: "$$REMOVE", else: 1} }
  3. revertir con $group
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!