When working with the "array" form, all you need to do is specify the field using "dot notation" to access the array member:
db.collection.find({}, { "positions.quantity": 1, })
This query would return:
{
"_id" : "2",
"positions" : [
{ "quantity" : "13" },
{ "quantity" : "24" }
]
}
If you want to retrieve multiple fields but exclude the "direction" field, you can simply include both fields in the projection:
db.collection.find({},{ "positions.name": 1, "positions.quantity": 1 })
Which would result in:
{
"_id" : "2",
"positions" : [
{
"name" : "APPL",
"quantity" : "13"
},
{
"name" : "GOOG",
"quantity" : "24"
}
]
}
For the "named keys" form, you will need to specify each path individually:
db.collection.find({},{ "positions.APPL.quantity": 1, "positions.GOOG.quantity": 1 })
This query would yield:
{
"_id" : "2",
"positions" : {
"APPL" : {
"quantity" : "13"
},
"GOOG" : {
"quantity" : "24"
}
}
}
Using "named keys" can be cumbersome and inefficient for MongoDB operations, as it requires JavaScript evaluation for traversing keys. This approach is not ideal due to the increased interpreter cost and lack of index optimization for queries. To manipulate output documents using JavaScript expressions, you would need to resort to using mapReduce, which can be impractical for regular operations.
Overall, utilizing an array structure with common paths is generally more efficient and practical than using named keys. Consistent object naming is encouraged for better organization and performance in MongoDB queries.