Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb execute multiple queries in one round trip

Is there anything like elasticsearch Multi Search API ? the link is : https://www.elastic.co/guide/en/elasticsearch/reference/current/search-multi-search.html.

consider I have multiple queries and I want to give these queries to mongo and get result in order .

like image 263
Majid Abdolhosseini Avatar asked Oct 21 '18 07:10

Majid Abdolhosseini


1 Answers

Yes, there is something similar in MongoDB. Using Aggregation Framework you can define multiple aggregation pipelines inside $facet stage.

Try:

db.col.save({a:1})
db.col.save({a:2})


db.col.aggregate([
    {
        $facet: {
            query1: [ { $match: { a:1 } }, { $project: { _id: 0 } } ],
            query2: [ { $match: { a:2 } }, { $project: { _id: 0 } } ],
        }
    }
])

which prints:

{ "query1" : [ { "a" : 1 } ], "query2" : [ { "a" : 2 } ] }

Using $facet you have to keep in mind that single BSON document can't exceed 16 MB size. More about aggregation limitations here

like image 153
mickl Avatar answered Oct 17 '22 21:10

mickl