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

168
Views
Mangosta Obtener campo con condición

Tengo un esquema como este:

 parentId: Number name:[ new Schema({ language: { type: String, enum: ['en-US', 'fr-CA'] }, text: String, },{ _id: false } ); ], isActive: Boolean ...

y muestra datos como los siguientes:

 { parentId:1, "name": [ {"language": "en-US", "text": "Book"}, {"language": "fr-CA", "text": "livre"} ], isActive:true // and so many other fields }, { parentId:1, "name": [ {"language": "en-US", "text": "Pen"} ], isActive:true // and so many other fields }

mi mangosta buscando textos en francés:

 db.langs.find({ "name.language":"fr-CA", parentId: 1 })

Q1. ¿Cómo puedo devolver el nombre en francés así:

 { parentId:1, "name": "livre", isActive:true // and so many other fields }

Q2. ¿Hay alguna posibilidad en mongoose de que pueda devolver el texto en francés y si el francés no está allí, devuelve el inglés?

 { parentId:1, "name": "livre", isActive:true // and so many other fields }, { parentId:1, "name": "pen", isActive:true // and so many other fields }
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Pregunta 1:

Puede usar $unwind para deconstruir la matriz y $match como un objeto. Y al menos haga $addFields para sobrescribir el campo de name con el valor deseado (si hay varios campos, es mejor que usar $project ). Todo esto en una tubería de agregación como esta:

 db.collection.aggregate([ { "$match": { "parentId": 1 } }, { "$unwind": "$name" }, { "$match": { "name.language": "fr-CA" } }, { "$addFields": { "name": "$name.text" } } ])

Ejemplo aquí

Pregunta 2:

Puede usar $facet para crear "dos formas". Uno si existe resultado francés y otro si no existe. Y luego verifique si existe para generar un valor u otro como este:

 db.collection.aggregate([ { "$match": { "parentId": 1 } }, { "$unwind": "$name" }, { "$facet": { "french": [ { "$match": { "name.language": "fr-CA" } } ], "notFrench": [ { "$match": { "name.language": "en-US" } } ] } }, { "$project": { "result": { "$cond": { "if": { "$eq": [ { "$size": "$french" }, 0 ] }, "then": "$notFrench", "else": "$french" } } } } ])

Ejemplo aquí

about 4 years ago · Juan Pablo Isaza Report

0

También puede hacerlo con operaciones de matriz.

consulta1

  • emparejar padre 1
  • fitler para mantener solo francés, y tomar el text
  • hacer coincidir para tener un nombre (para eliminar documentos que no tenían un libro en francés)

Código de prueba aquí

 aggregate( [{"$match": {"parentId": {"$eq": 1}}}, {"$set": {"name": {"$getField": {"field": "text", "input": {"$arrayElemAt": [{"$filter": {"input": "$name", "cond": {"$eq": ["$$this.language", "fr-CA"]}}}, 0]}}}}}, {"$match": {"$expr": {"$eq": [{"$type": "$name"}, "string"]}}}])

consulta2

  • emparejar padre 1
  • reducir
    • si el valor (lo encontré antes) francés lo guardo
    • de lo contrario, si el actual es Francia, me quedo con esto
    • de lo contrario, si los actuales somos nosotros, me quedo con esto
    • else value (mantener el valor inicial que está vacío {})
  • hacer coincidir para tener un nombre (para eliminar documentos que no tenían un libro francés o estadounidense)

Código de prueba aquí

 aggregate( [{"$match": {"parentId": {"$eq": 1}}}, {"$set": {"name": {"$getField": {"field": "text", "input": {"$reduce": {"input": "$name", "initialValue": {}, "in": {"$switch": {"branches": [{"case": {"$eq": ["$$value.language", "fr-CA"]}, "then": "$$value"}, {"case": {"$eq": ["$$this.language", "fr-CA"]}, "then": "$$this"}, {"case": {"$eq": ["$$this.language", "en-US"]}, "then": "$$this"}], "default": "$$value"}}}}}}}}, {"$match": {"$expr": {"$eq": [{"$type": "$name"}, "string"]}}}])
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!