0

I am working on a collection called Publications. Each publication has an array of objectives which are ids. I have also a custom array of objectives hand written. Now, I want to select all the publications that contains at least one element of the custom objectives array in their objectives. How can I do that ?

I've been trying to make this works with '$setIntersection' then '$count' and verify that the count is greater than 0 but I don't know how to implement this.

Example :

publication_1: {
     '_id': ObjectId("sdfsdf46543")
     'objectives': [ObjectId("1654351456341"), ObjectId("123456789")]
}

publication_2: {
     '_id': ObjectId("sdfs216546543")
     'objectives': [ObjectId("1654351456341"), ObjectId("46531132")]
}

custom_array = [ObjectId("123456789"), ObjectId("2416315463")]

The mongo query should return publication_1.

2 Answers 2

1

You can do like the following:

db.publications.find({
  "objectives": {
    "$in": [
      ObjectId("123456789"),
      ObjectId("2416315463")
    ]
  }
})

Notice: "123456789" is not a valid ObjectId so the query itself may not work. Here is the working example

Mongodb playground link: https://mongoplayground.net/p/MbZK99Pd5YR

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

Comments

0

objectives is an array of objects, I guess you can just query that field directly:

let custom_array = [ObjectId("123456789"), ObjectId("2416315463")];
// You can search the array with $in property. 
let result = await Model.find({ objectives: {$in : custom_array} })

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.