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 }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í
También puede hacerlo con operaciones de matriz.
consulta1
text 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
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"]}}}])