简体   繁体   中英

Using $match on an embedded document in an aggregate

I am trying to use $match to find items with a specific _id in a double embedded document.

I have a document called users which contains information such as name, email, and it also contains an embedded document which has the business this user is with.

I also have a document called businesses, which contains an embedded document which has the building that this business is in.

I also have a document called building.

I am trying to have a mongo query which returns all of the users with a business at a certain building ID.

I have an aggregate function which uses $lookup to match the users to the building they are in. and this does work. However now I am trying to use $match to only return the documents with a specific building id.

Here is an example of my user, business and building documents:

_id: 5ca487c0eeedbe8ab59d7a7a
name: "John Smith"
email: "jsmith9@gmail.com"
business: Object
  _id: 5ca48481eeedbe8ab59d7a38
  name: "Visitors"


_id: 5ca48481eeedbe8ab59d7a38
name: "Visitors"
building: Object
  _id: 5ca48481eeedbe8ab59d7a36
  name: "Building1"


_id: 5ca48481eeedbe8ab59d7a36
name: "Building1"

When I return the aggregated query it returns documents in the following format:

    {
        "_id": "5ca487c0eeedbe8ab59d7a7a",
        "name": "John Smith",
        "email": "jsmith9@gmail.com",
        "business": {
            "_id": "5ca48481eeedbe8ab59d7a38",
            "name": "Visitors"
        },
        "__v": 0,
        "user_building": {
            "_id": "5ca48481eeedbe8ab59d7a38",
            "name": "Visitors",
            "building": {
                "_id": "5ca48481eeedbe8ab59d7a36",
                "name": "Building1"
            },
            "__v": 0
        }
    },

However when I add the match in, it returns []. What am i doing wrong here?

router.get("/:id", async (req, res) => {
  const users_buildings = await User.aggregate([
    {
      $lookup: {
        from: "businesses",
        localField: "business._id",
        foreignField: "_id",
        as: "user_building"
      }
    },
    { $unwind: "$user_building" },

    {
      $match: {
        "user_building.building": { _id: req.params.id }
      }
    }
  ]);

You need to match _id inside the building object. Try with this

 {
  $match: {
    "user_building.building._id": req.params.id
  }
}

if not working

{
  $match: {
    "user_building.building._id": ObjectId(req.params.id)
  }
}

op edit: I imported ObjectId with:

var ObjectId = require('mongodb').ObjectID;

and used the second solution and it worked correctly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM