Guy Joseph
Guy Joseph

Reputation: 50

Ensure an array of documents exist in a collection

I have a collection with approximately 40k documents that look like this:

{

    "_id":{"$oid":"5e988b703117c034b0630f8"},
    "name":"London Heathrow Airport",
    "country":"United Kingdom",
    "iata":"LHR",
    ...
}

I want to be able to work through an array (actually a Javascript Map, which could have many hundreds of elements) like this:

["LHR", "LGW", "BFS", ...]

The items in this array relate to the iata property on the document.

I want to return an array where the elements that cannot be found in the collection are returned, and if all elements can be found then to return either a null value or empty array. So for example if "LHR" and "LGW" match the iata property of a document in the collection, but "BFS" doesn't, it should return ["BFS"]

I could interate through the array, making an individual query for each item in the array, but if the input array has many hundreds of elements, this seems very inefficient. Is there a better way!?

Thanks

Upvotes: 0

Views: 34

Answers (1)

Caconde
Caconde

Reputation: 4493

You can query your collection for matching iata codes and do a diff between the result and your array of iata codes:

Given a collection airports with the following documents:

{
    "_id": 1,
    "name":"London Heathrow Airport",
    "country":"United Kingdom",
    "iata":"LHR",
},
{
    "_id": 2,
    "name":"Ljubljana Airport",
    "country":"Slovenia",
    "iata":"LJU",
},

Given the array of iata below:

var iatas = ["LHR", "LJU", "BFS"];

Find the matching documents and return result as an array of iata values:

var result = [];
db.airports.find({
    "iata": {
        $in: iatas
    }
}).toArray().map( 
    function(u) {
        result.push(u.iata)
    }
);

The result will look like:

//result
[
    "LHR",
    "LJU"
]

Now you can do a diff between result and iatas:

var nonexistentIatas = iatas.filter(x => !result.includes(x));

The content of nonExistentIatas will be:

[
    "BFS"
]

Upvotes: 1

Related Questions