Arun Muthupalaniappan
Arun Muthupalaniappan

Reputation: 170

How to use result of a query as match parameter conditions in another query (MongoDB)?

I did an aggregate query and the result of the query is this :

{ "_id" : "Tom" }
{ "_id" : "Jack" }

I need to display all the records that contain Tom and Jack in the field 'host_name'. How do I go about this?

I tried to convert it into an array and store it in a variable named k and use it in a match aggregation, but does not seem to work, this is what I did :

k = db.abnb.aggregate([{$match: {"host_is_superhost": "t"}}, {$group: {"_id": "$host_name"}}, {$limit: 2} ]);
db.abnb.aggregate([ { $match : { host_name : k } } ])

Upvotes: 0

Views: 280

Answers (2)

Belly Buster
Belly Buster

Reputation: 8814

Get your query results into a list and use $in:

from pymongo import MongoClient
#
# Set some data up
#
db = MongoClient()['mydatabase']
db.abnb.insert_many([{'host_name': 'Tom'}, {'host_name': 'Dick'}, {'host_name': 'Harry'}, {'host_name': 'Jack'}])
agg1 = [{"_id": "Tom"}, {"_id": "Jack"}]
#
# This is the meat of it
#
result = db.abnb.find({'host_name': {'$in': [x['_id'] for x in agg1]}})

print(list(result))

prints:

[{'_id': ObjectId('606dfa4e4252a193402ce182'), 'host_name': 'Tom'}, {'_id': ObjectId('606dfa4e4252a193402ce185'), 'host_name': 'Jack'}]

Upvotes: 1

AlexisG
AlexisG

Reputation: 2474

The field host_name is a temporary variable, it's only accessible in your aggregate.

If you want to save the result of your aggregate, you will need to use $out (see the doc)

Upvotes: 0

Related Questions