sql >> Base de Datos >  >> NoSQL >> MongoDB

Consulta de mangosta:encuentra un elemento dentro de una matriz

Usando el $ operador posicional, puede obtener los resultados. Sin embargo, si tiene varios elementos en los vehicles arreglo, todos ellos se devolverán en el resultado, ya que solo puede usar un operador posicional en la proyección y está trabajando con 2 arreglos (uno dentro de otro).

Le sugiero que eche un vistazo al aggregation framework , ya que obtendrá mucha más flexibilidad. Aquí hay una consulta de ejemplo para su pregunta que se ejecuta en el shell. No estoy familiarizado con la mangosta, pero supongo que esto te ayudará y podrás traducirlo:

db.collection.aggregate([
    // Get only the documents where "email" equals "[email protected]" -- REPLACE with params.username
    {"$match" : {email : "[email protected]"}}, 
    // Unwind the "inventories" array
    {"$unwind" : "$inventories"}, 
    // Get only elements where "inventories.title" equals "activeInventory"
    {"$match" : {"inventories.title":"activeInventory"}}, 
    // Unwind the "vehicles" array
    {"$unwind" : "$inventories.vehicles"}, 
    // Filter by vehicle ID -- REPLACE with vehicleID 
    {"$match" : {"inventories.vehicles._id":ObjectId("53440e94c02b3cae81eb0069")}}, 
    // Tidy up the output
    {"$project" : {_id:0, vehicle:"$inventories.vehicles"}}
])

Este es el resultado que obtendrá:

{
        "result" : [
                {
                        "vehicle" : {
                                "_id" : ObjectId("53440e94c02b3cae81eb0069"),
                                "tags" : [
                                        "vehicle"
                                ],
                                "details" : [
                                        {
                                                "_id" : ObjectId("53440e94c02b3cae81eb0066"),
                                                "year" : 2007,
                                                "transmission" : "Manual",
                                                "price" : 1000,
                                                "model" : "Firecar",
                                                "mileageReading" : 50000,
                                                "make" : "Bentley",
                                                "interiorColor" : "blue",
                                                "history" : "CarProof",
                                                "exteriorColor" : "blue",
                                                "driveTrain" : "SWD",
                                                "description" : "test vehicle",
                                                "cylinders" : 4,
                                                "mileageType" : "kms"
                                        }
                                ]
                        }
                }
        ],
        "ok" : 1
}