user44552
user44552

Reputation: 161

Query for field in subdocument

An example of the schema i have;

{ "_id" : 1234,
  “dealershipName”: “Eric’s Mongo Cars”,
  “cars”: [
         {“year”: 2013,
           “make”: “10gen”,
           “model”: “MongoCar”,
           “vin”: 3928056,
           “mechanicNotes”: “Runs great!”},
         {“year”: 1985,
          “make”: “DeLorean”,
          “model”: “DMC-12”,
          “vin”: 8056309,
          “mechanicNotes”: “Great Scott!”}
         ]
  }

I wish to query and return only the value "vin" in "_id : 1234". Any suggestion is much appreciated.

Upvotes: 1

Views: 111

Answers (2)

JohnnyHK
JohnnyHK

Reputation: 312129

You can use the field selection parameter with dot notation to constrain the output to just the desired field:

db.test.find({_id: 1234}, {_id: 0, 'cars.vin': 1})

Output:

{
    "cars" : [ 
        {
            "vin" : 3928056
        }, 
        {
            "vin" : 8056309
        }
    ]
}

Or if you just want an array of vin values you can use aggregate:

db.test.aggregate([
    // Find the matching doc
    {$match: {_id: 1234}},
    // Duplicate it, once per cars element
    {$unwind: '$cars'},
    // Group it back together, adding each cars.vin value as an element of a vin array
    {$group: {_id: '$_id', vin: {$push: '$cars.vin'}}},
    // Only include the vin field in the output
    {$project: {_id: 0, vin: 1}}
])

Output:

{
    "result" : [ 
        {
            "vin" : [ 
                3928056, 
                8056309
            ]
        }
    ],
    "ok" : 1
}

Upvotes: 2

grant
grant

Reputation: 872

If by query, you mean get the values of the vins in javascript, you could read the json into a string called theString (or any other name) and do something like:

var f = [], obj = JSON.parse(theString);

obj.cars.forEach(function(item) { f.push(item.vin) });

If your json above is part of a larger collection, then you'd need an outer loop.

Upvotes: 0

Related Questions