1

Let's say I have a collection, like so:

[
{ "_id": "101",  parts: [1.2, 2] },
{ "_id": "102",  parts: [2, 3.5] },
{ "_id": "103",  parts: [4.1, 10] }
]

What is the query I need to write so that each item in the array parts is greater than equal to the item with the same array index in an input array [1, 5]?

output would be:

[
{ "_id": "103",  parts: [4.1, 10] } // 4.1 >= 1 and 10 >= 5
]

is this possible? any idea?

2
  • The parts array and the input array have same number of elements? Commented Sep 16, 2020 at 8:53
  • yes, same number of elements @prasad_ Commented Sep 16, 2020 at 9:19

2 Answers 2

1

You can use the dot notation and run following query for your example:

{"parts.0":{"$gte":1},"parts.1":{"$gte":5}}

Mongo Playground

or use below JS code to build something more generic:

let input = [1,5];
let query = Object.fromEntries(input.map((val, i) => ([ "parts." + i, { $gte: val } ])));

console.log(query);

Sign up to request clarification or add additional context in comments.

Comments

1

If you know the input array before query then you can create query object from it first then pass this object to the query:

let query = input.reduce((acc, cur, index) => {
  acc['parts.' + index] = { $gt: cur };
  return acc;
}, {});
// [1, 5] will create {"parts.0": {$gt: 1},"parts.1": {$gt: 5}}
db.collection.find(query)...

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.