[SERVER-1831] Using dot-notation to field-select an element by position from a nested Array fails to return the element Created: 22/Sep/10  Updated: 06/Dec/22

Status: Backlog
Project: Core Server
Component/s: Querying
Affects Version/s: 1.6.2
Fix Version/s: None

Type: New Feature Priority: Major - P3
Reporter: Glenn Powell Assignee: Backlog - Query Optimization
Resolution: Unresolved Votes: 15
Labels: query-44-grooming
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Mac OSX 64bit


Issue Links:
Duplicate
is duplicated by SERVER-5299 array element selection syntax return... Closed
Related
is related to SERVER-50504 $facet+$match on positional path does... Closed
Assigned Teams:
Query Optimization
Participants:

 Description   

It seems reasonable that if dot-notation works as a field-selector when selecting object members, that it should also work when selecting array indexes,
but that doesn't seem to be the case with the current version of MongoDB.
Case:

// Get the entire array (succeeds):
 
> db.foo.find({"key":"12345"}, {"array_field"})
 
{ "_id" : ObjectId("4c9a41204cb16aa4fe28c4cc"), "array_field" : [
        {
                "bar" : "data",
                "bam" : "more data",
        }
] }
 
 
// Attempt to get first element in array (index 0):
 
> db.foo.find({"key":"12345"}, {"array_field.0":1})
 
{ "_id" : ObjectId("4c9a41204cb16aa4fe28c4cc"), "array_field" :
[ { } ] } 

The second command fails to return anything. You can in fact use the $slice operator to get the element, but then the command becomes large and ugly:

> db.foo.find({"key":"12345"}, {_id:1, array_field:{$slice:[0,1]}}) 

When developing custom ORM classes to access Mongo, this special case will be needed when accessing an array element by index. This seems unnecessary.
I suggest that Mongo handle dot-notation the same for Arrays as it already does for Objects, and simply allow you to select by index. (Note, that a find query does allow array indexes in the dot notation, but the field select param does not)



 Comments   
Comment by David Storch [ 12/Jul/19 ]

Projection does not currently support the concept of including or excluding by array index, either in the find command or in aggregate's $project stage. We should add this as a new feature, though it would likely involve the introduction of new syntax, e.g. find(<match>, {"arr.$[0]": 1}) for including only the first element of the array arr.

Comment by vishnu v l [ 07/Aug/12 ]

It is very reasonable since mongodb design drives people to prefer embedding and one does not want to fetch all the array elements into program memory.

Generated at Thu Feb 08 02:58:10 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.