1

I have a collection of documents that goes like this:

{
  name: "Whatever 1".
  distances: [
    {name: "first distance", distance: 3000},   
    {name: "another distance", distance: 8000},
  ]
},
{
  name: "Whatever 2".
  distances: []
},
{
  name: "Whatever 3".
  distances: [
    {name: null, distance: 6000},   
  ]
},
{
  name: "Whatever 4".
  distances: [
    {name: "hello", distance: 100000},   
  ]
},

I need to get all the documents that contains a distance in a given range.

Example: If I query for distance greater than 5000 and smaller than 9000, I want to get documents "Whatever 1" and "Whatever 3"

How can I do this?

1 Answer 1

1

You can use $elemMatch to specify range condition for single subdocument of distances array:

db.col.find({ distances: { $elemMatch: { distance: { $gt: 5000, $lt: 9000 } } } })
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.