0

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 ?

1 Answer 1

1

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 ] }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.