Home > Enterprise >  How can I get the documents having an id that are attribute values of another document in mongodb?
How can I get the documents having an id that are attribute values of another document in mongodb?

Time:01-20

This is an exemple:

{"_id": 1,
"attr1": "x",
"class":"vehicle"}
{"_id": 2,
"attr1": "xf",
"class":"vehicle"}
{"_id": 3,
"attr1": "xz",
"class":"vehicle"}
{"_id": 4,
"attr1": "xddz",
"class":"vehicle"}

{"_id": 11,
"attr1": "xy",
"class":"seat",
"vehicle":[1,2]}

{"_id": 12,
"attr1": "exy",
"class":"seat",
"vehicle":[3,2]}

I would like to know what query or aggregate to use in order to get the document with "class" vehicle having their ids in the array of attribute value of the documents with class "seat".

In our example I need to have those documents returned:

{"_id": 1,
"attr1": "x",
"class":"vehicle"}
{"_id": 2,
"attr1": "xf",
"class":"vehicle"}
{"_id": 3,
"attr1": "xz",
"class":"vehicle"}

CodePudding user response:

Assuming every document is in the same collection, you could do something like this :

db.collection.aggregate([
  {
    "$group": {
      "_id": null,
      "root": {
        "$push": "$$ROOT"
      },
      
    }
  },
  {
    $project: {
      _id: 0,
      res: {
        "$filter": {
          "input": "$root",
          "as": "values",
          "cond": {
            $in: [
              "$$values._id",
              {
                "$reduce": {
                  input: "$root.vehicle",
                  initialValue: [],
                  in: {
                    "$setUnion": [
                      "$$value",
                      "$$this"
                    ]
                  },
                  
                }
              },
              
            ]
          }
        }
      }
    }
  },
  {
    "$unwind": "$res"
  },
  {
    "$replaceRoot": {
      "newRoot": "$res"
    }
  }
])

You can check on https://mongoplayground.net/p/iYG8o0ZOde5

  • Related