0

If I were to write this in SQL it would be (sort of):

SELECT *
FROM request req, response res
WHERE req.suites_test=res.key    # join
  AND res.version='2.0.b1662.5'  # extra conditions
  AND req.suites_id='58762c40664df86d2069e2c9'

In MongoDB I can do:

# a join between request and response 
db.response.aggregate([{$lookup: {from: "request", localField: "key", foreignField: "suites.test", as: "matching"} } ])

# find all requests that match a condition
db.request.find( { "suites.id": ObjectId("58762c40664df86d2069e2c9") } )

# find all responses that match a condition
db.response.find( { "version": "2.0.b1662.5" } )

How can I combine the three in a single MongoDB query?

chridam
  • 100,957
  • 23
  • 236
  • 235
SkyWalker
  • 13,729
  • 18
  • 91
  • 187

1 Answers1

1

There are a bunch of duplicates which are similar, but I can't find the exact matching duplicate. So, I'm adding an answer based on OP's request.

Based on your individual queries, you will just need to include the $match stage for the response ( before $lookup) and request ( after $unwind which follows $lookup ) collection in your aggregation pipeline. Something like below.

db.response.aggregate([{
    $match: {
        "version": "2.0.b1662.5"
    }
}, {
    $lookup: {
        from: "request",
        localField: "key",
        foreignField: "suites.test",
        as: "matching"
    }
}, {
    $unwind: "$matching"
}, {
    $match: {
        "matching.id": ObjectId("58762c40664df86d2069e2c9")
    }
}])
s7vr
  • 73,656
  • 11
  • 106
  • 127
  • 1
    It is because you can't find an exact duplicate that we call it *possible duplicates* – styvane Jan 17 '17 at 14:55
  • 1
    At the end you just pollute the SO with these possible duplicates and is no wonder that I find questions that are marked as possible duplicates of other questions that have nothing to do with what I was originally looking for, thus polluting SO with ping-pong possible duplicates. – SkyWalker Jan 17 '17 at 14:58
  • Understood, but I felt possible duplicates are not closer to OP's question but its purely one's perspective. – s7vr Jan 17 '17 at 14:58
  • 1
    Now anyone looking for a simple way to mix join and where clauses will find it in this in this Q/A instead of bouncing around in SO hopelessly. – SkyWalker Jan 17 '17 at 14:59