Lukas
Lukas

Reputation: 10340

Matching a set of items containing arrays in MongoDB

Let's say I have the following data

[
  { name: 'A', values: [1, 2, 3 ,4] },
  { name: 'B', values: [5, 6, 7, 8] }
]

and I have a mongodb that has the following items in a collection:

#1 { name: 'A', values: [1, 2, 3 ,4], path: '...' },
#2 { name: 'B', values: [8, 9, 5, 7], path: '...' },
#3 { name: 'B', values: [5, 6, 7, 8], path: '...' },
#4 { name: 'C', values: [9, 10, 11, 12], path: '...' }

Now I want to query the paths that match my 2 items A and B from the data (Items #1 and #3). Is that possible edit: with a single query?

Upvotes: 1

Views: 29

Answers (1)

Ashh
Ashh

Reputation: 46441

You can loop through the data and use query inside the map function by making it asynchronous

const data = [
  { name: 'A', values: [1, 2, 3 ,4] },
  { name: 'B', values: [5, 6, 7, 8] }
]

const result = []
await Promise.all(data.map(async(d) => {
  result.push(await db.collection.findOne(d))
}))

Or even with the single query

await db.collection.find(
  {
    name: { $in: data.map(({ name }) => name) },
    values: { $in: data.map(({ values }) => values) }
  }
)

Upvotes: 2

Related Questions