Search on multiple collections in MongoDB

前端 未结 7 1989
自闭症患者
自闭症患者 2020-12-01 01:28

I know the theory of MongoDB and the fact that is doesn\'t support joins, and that I should use embeded documents or denormalize as much as possible, but here goes:

7条回答
  •  孤街浪徒
    2020-12-01 02:06

    So now join is possible in mongodb and you can achieve this using $lookup and $facet aggregation here and which is probably the best way to find in multiple collections

    db.collection.aggregate([
      { "$limit": 1 },
      { "$facet": {
        "c1": [
          { "$lookup": {
            "from": Users.collection.name,
            "pipeline": [
              { "$match": { "first_name": "your_search_data" } }
            ],
            "as": "collection1"
          }}
        ],
        "c2": [
          { "$lookup": {
            "from": State.collection.name,
            "pipeline": [
              { "$match": { "name": "your_search_data" } }
            ],
            "as": "collection2"
          }}
        ],
        "c3": [
          { "$lookup": {
            "from": State.collection.name,
            "pipeline": [
              { "$match": { "name": "your_search_data" } }
            ],
            "as": "collection3"
          }}
        ]
      }},
      { "$project": {
        "data": {
          "$concatArrays": [ "$c1", "$c2", "$c3" ]
        }
      }},
      { "$unwind": "$data" },
      { "$replaceRoot": { "newRoot": "$data" } }
    ])
    

提交回复
热议问题