Ashish
Ashish

Reputation: 363

Retaining array keys after using slice in MongoDB with PHP

I have a MongoDB object of following structure:

{
"_id": ObjectId("4f5ed7d33c9059a00d000002"),
"data":
{
"0": "data1",
"1": "data2",
"2": "data3",
"3": "data4",
}
}

I am using the following code to retrieve sliced result:

$obj1 = $collection->findOne(array('_id' => new MongoId('4f5ed7d33c9059a00d000002')),array('_id'=>1,'data'=>array('$slice' =>2 )));

But the result of this query does not retain array indexes of array data.

Upvotes: 1

Views: 203

Answers (1)

Karoly Horvath
Karoly Horvath

Reputation: 96258

You can use the $slice operator to retrieve a subrange of elements in an array.

What you are trying to slice is a document (subdocument). Arrays use fixed positions for the elements, [0..(numelements-1)] so there's no way to keep the "indexes". Unfortunately php's equivalent of a document is an associative array hence the confusion.

Upvotes: 1

Related Questions