I have a document in my collection with an array field:
location {
[0] = 1.99999
[1] = 3.6544321
}
How can I filter by values of array field ?
How can I show only location[0] in find query ?
How can I show only location[0] in find query ?
Use $slice to show only the desired element on the array
Sample Documents in a collection
{ "_id" : ObjectId("5a3231d1bf7e914583df4fbf"), "location" : [ 1.99999, 3.6544321 ] }
{ "_id" : ObjectId("5a3231e1bf7e914583df4fc0"), "location" : [ 23.99999, 43.6343341 ] }
{ "_id" : ObjectId("5a3231f5bf7e914583df4fc1"), "location" : [ 12.2323, 11.2879731 ] }
Mongo Shell Query
db.collection_name.find({},{"location":{$slice:[0,1]}});
Results
{ "_id" : ObjectId("5a3231d1bf7e914583df4fbf"), "location" : [ 1.99999 ] }
{ "_id" : ObjectId("5a3231e1bf7e914583df4fc0"), "location" : [ 23.99999 ] }
{ "_id" : ObjectId("5a3231f5bf7e914583df4fc1"), "location" : [ 12.2323 ] }
How can I filter by values of array field ?
Use $elemMatch to filter the array elements by values
Mongo Shell query
db.collection_name.find({location:{$elemMatch:{$gte:12}}})
Results
{ "_id" : ObjectId("5a3231e1bf7e914583df4fc0"), "location" : [ 23.99999, 43.6343341 ] }
{ "_id" : ObjectId("5a3231f5bf7e914583df4fc1"), "location" : [ 12.2323, 11.2879731 ] }