Dylan
Dylan

Reputation: 1348

MongoDB How to check if all ObjectIds inside the array exist in the database?

I have an array containing multiple mongodb ObjectId, how can I know if all that Ids exist in the specific collection,

Although I can achieve my expected result by for loop like this, it will take too long to load because it will make multiple query for how many index my array has.

const queryData = async objectIds => {
    // objectIds contains an array of ObjectId

    for (let i = 0; i < objectIds.length; i++) {
        const objId = objectIds[i]
        const data = await DataCollection.findOne({ _id: objId })

        if (!data) throw new Error('Data not found!')
    }
}

how can I achieve the same result as my sample function without querying multiple times that makes the process so much slower?

Upvotes: 2

Views: 809

Answers (1)

mickl
mickl

Reputation: 49975

You can use .count() and $in for filtering condition:

let count = await DataCollection.count( { _id: { $in: objectIds } } );
let all = count === objectIds.length;

Upvotes: 2

Related Questions