Mongo db subquery with same collection

Viewed 262

I'm trying to sub query data with single collection.

Equivalent SQL query:

Select * from customer where custid = (select custid from customer where device ID = 123 and date <= currentdate fetch first row only) where date<= current date
1 Answers

You can subquery in MongoDB by using a $lookup within an aggregation.

If your query was db.items.find({ tag: 'blue' }) you can convert that to an aggregation like

db.items.aggregate([
{ $match: { tag: 'blue' } },
{ $lookup: your_lookup_command }
])

See https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/ for $lookup syntax. If you're on MongoDB 3.6 or newer, you can use another embedded aggregation to return more complex subqueries with grouping or advanced filtering.

Related