12

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 .

1 Answer 1

18

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

Sign up to request clarification or add additional context in comments.

3 Comments

Note that if you need to provide a hint for this query, this is possible only in MongoDB version 3.6 or later
To clarify, you might need to provide a hint, because otherwise mongo will probably not use an index, due to: jira.mongodb.org/browse/SERVER-30474
Thank you @Joe for your comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.