Breeky
Breeky

Reputation: 61

MongoDB : Match with element in an array

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.

Upvotes: 0

Views: 45

Answers (2)

glinda93
glinda93

Reputation: 8459

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

Upvotes: 1

ibrahimijc
ibrahimijc

Reputation: 341

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} })

Upvotes: 0

Related Questions