[SERVER-5565] Handle negative array offsets consistently Created: 10/Apr/12  Updated: 10/Dec/14  Resolved: 05/Dec/13

Status: Closed
Project: Core Server
Component/s: Write Ops
Affects Version/s: None
Fix Version/s: None

Type: Bug Priority: Minor - P4
Reporter: Richard Kreuter (Inactive) Assignee: Unassigned
Resolution: Done Votes: 1
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Operating System: ALL
Participants:

 Description   

update, find, and $slice don't agree about what negative integers mean: $slice treats negatives as offsets from the right end of the array, find doesn't (seem to) support them at all, and update does something weird:

db.a.insert({ x : [] });
db.a.update({}, { $set : { "x.-1" : 1 } } );
db.a.update({}, { $set : { "x.-1" : 2 } } );
db.a.update({}, { $set : { "x.-1" : 3 } } );
db.a.find()
{ "_id" : ObjectId("4f849706fdbf7f54d34ba15b"), "x" : [ 3, 2, 1 ] }
db.a.find({}, { x: { $slice : -1 } })
{ "_id" : ObjectId("4f849706fdbf7f54d34ba15b"), "x" : [ 1 ] }
db.a.find({ "x.-1" : 1 });

I didn't check what aggregation framework operators do...



 Comments   
Comment by Scott Hernandez (Inactive) [ 05/Dec/13 ]

I checked with query and aggregation and things now seem consistent.

Please reopen if you find more things.

Comment by Scott Hernandez (Inactive) [ 05/Dec/13 ]

Kurt, you can now, when 2.6 stable is out, use $position to specify the position to push into an array with, so this is probably what you want.

// push to the front of the array
db.a.update({}, { $push : { x : { $each: [1], $position:0 }}} );

Richard, this is no longer supported in updates (albeit with a less than optimal error message):

 db.arrays.update({}, {$set:{"a.-1":12}})
cannot use the part (a of a.-1) to traverse the element ({a: [ 1.0, 12.0 ]})
Update WriteResult({
	"ok" : 0,
	"code" : 16837,
	"errmsg" : "cannot use the part (a of a.-1) to traverse the element ({a: [ 1.0, 2.0 ]})",
	"n" : 0
})
> db.arrays.find()
{ "_id" : 1, "a" : [ 1, 2 ], "b" : [ 2, 1 ] }
Fetched 1 record(s) in 1ms

Comment by Kurt Agius [ 11/Feb/13 ]

The update -1 is a requirement which i think is quiet common.

So we need to update the last item in the array, which is expected to be:

db.a.update({}, { $set :

{ "x.-1" : 1 }

} );

Any idea if this is planned to be supported very soon ?
Or is there any particular logic behind the current behavior of the statement above ?

Generated at Thu Feb 08 03:09:17 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.