MongoDB
 sql >> Database >  >> NoSQL >> MongoDB

Query Mongoose:trova un elemento all'interno di un array

Utilizzando $ operatore posizionale, puoi ottenere i risultati. Tuttavia, se hai più elementi in vehicles array tutti verranno restituiti nel risultato, poiché puoi utilizzare solo un operatore posizionale nella proiezione e stai lavorando con 2 array (uno dentro l'altro).

Ti suggerirei di dare un'occhiata al aggregation framework , poiché otterrai molta più flessibilità. Ecco una query di esempio per la tua domanda che viene eseguita nella shell. Non ho familiarità con la mangusta, ma immagino che questo ti aiuterà comunque e saresti in grado di tradurlo:

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"}}
])

Questo è l'output che otterrai:

{
        "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
}