0

I have a mongodb collection with an array of objects. I want to be able to search the objects in the array in any order and only return a match if all objects in that array are found.

My collection:

{
    "_id" : ObjectId("5234c367354kj63c9cae4fec"),
    "field1" : "TEST",
    "created" : <DATE_HERE>,
    "field2" : [ 
        {
            "index" : "A",
            "value" : "1"
        }, 
        {
            "index" : "B",
            "value" : "2"
        }, 
        {
            "index" : "C",
            "value" : "3"
        }
    ],
}

If I provide the query below, the above document will get returned, because all 3 objects are given in the exact order that they're stored.

db.collection("collection").find({field1: "TEST", field2: [{"index": "A", "value": "1"}, {"index": "B", "value": "2"}, {"index": "C", "value": "3"}]})

However, I want to be able to find the document above given the 3 objects in any order. For example the query below:

db.collection("collection").find({field1: "TEST", field2: [{"index": "B", "value": "2"}, {"index": "A", "value": "1"}, {"index": "A", "value": "1"}]})

I know the above query won't work, if it's even possible, and is missing the correct syntax/search function, but it's just to explain my thought process and what i'm trying to achieve.

I've tried using the $in search with something like field2: {$in: [<3_objects_above>]}, but it won't give me an exact match. For example, if there's a 2nd document in this collection with field2: [...{"index": "Z", "value": "543"}] and it contains just 1 of 3 of the objects shown in the 2 queries and table above, this 2nd document would get returned as well because it matched at least 1 object provided in the array even though i didn't provide the object {"index": "Z", "value": "543"}.

Is there a way to accomplish giving objects in an array in any order and find the document in a collection that matches all 3 objects no matter what order they're given in? Matches all 3 not any of the 3?

1
  • No as i didn't know about that one, but i just tested and that worked!!! Thank you! Can you please respond to the post so i can accept your answer? Commented Feb 10, 2020 at 21:55

1 Answer 1

1

You can use the $all operator:

db.collection.find(
   {
      field1: "TEST",
      field2: {
         $all: [
            { "index": "A", "value": "1" },
            { "index": "B", "value": "2" },
            { "index": "C", "value": "3" }
         ]
      }
   }
)   
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.