Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Querying MongoDB to match in the first item in an array

I'm aware of the $in operator, which appears to search for an item's presence in array, but I only want to find a match if the item is in the first position in an array.

For instance:

{     "_id" : ObjectId("0"),     "imgs" : [         "http://foo.jpg",         "http://bar.jpg",         "http://moo.jpg",         ] }, {     "_id" : ObjectId("1"),     "imgs" : [         "http://bar.jpg",         "http://foo.jpg",         "http://moo.jpg",         ] } 

I'm looking for a query akin to:

db.products.find({"imgs[0]": "http://foo.jpg"}) 

This would/should return the ObjectId("0") but not ObjectId("1"), as it's only checking against the first image in the array.

How can this be achieved? I'm aware I could just create a separate field which contains a single string for firstImg but that's not really what I'm after here.

like image 730
JVG Avatar asked Nov 11 '13 05:11

JVG


People also ask

How do I match an array element in MongoDB?

The $elemMatch operator matches documents that contain an array field with at least one element that matches all the specified query criteria. If you specify only a single <query> condition in the $elemMatch expression, and are not using the $not or $ne operators inside of $elemMatch , $elemMatch can be omitted.

What does $first do in MongoDB?

$first selects the first document from each output group: The _id: null group is included. When the accumulator field, $quantity in this example, is missing, $first returns null .


1 Answers

I believe you want imgs.0. eg, given your example document, you want to say: db.products.find({"imgs.0": "http://foo.jpg"})

Be aware that referencing array indexes only works for the first-level array. Mongo doesn't support searching array indexes any deeper.

like image 174
poundifdef Avatar answered Sep 28 '22 02:09

poundifdef