Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return array index from $elemMatch query

Say I have a document like this

{
  title : 'myTitle',
  favorites : [{name : 'text', number : 6}, {name : 'other', number : 4}]
}

I would like to return the array index (if any) from where the embedded document was retrieved within the favorites array.

Say I have the following query

 {title : 'myTitle'}

and the projection

 {favorites : {$elemMatch : {name : 'text', number : 6} }}

if the projection returns the document AND it contains a favorites array with the sub document, is there a way to know at which index that sub document was found? Which in this case is index 0.

The reason I would like the index is because as soon as I retrieve the document, I proceed to update it, and it would boost the performance if I had a specific index to update instead of using $elemMatch again which would cause mongo to iterate through all the array entries until finding the document that matches.

like image 643
naughty boy Avatar asked Apr 25 '26 15:04

naughty boy


1 Answers

Unfortunately, it is not possible using the $elemMatch operator. If you are using mongodb 3.2, you could make use of the $unwind operator and aggregate instead of doing a find()

db.collection.aggregate([
{$match:{"favorites.name":"text","favorites.number":6}},
{$unwind:{"path":"$favorites","includeArrayIndex":"index"}},
{$match:{"favorites.name":"text","favorites.number":6}}
])

The document would be returned, with its array index in the field - index. If you want the entire document, with other array elements, you would have to $group, after $unwind instead of $match.

For previous versions, iterating the array in the client side, and getting the sub document's index would be the way to go.

like image 53
BatScream Avatar answered Apr 28 '26 04:04

BatScream