简体   繁体   中英

MongoDb - Join two collections filtering by actual document field and nested

I am using MongoDb and I'd like to join two collections, so that I am using $lookup :

collection USERS:

{
   userId: "123",
..
}

collection CARS:

{
   carId: "3bff06ea-e973-4335-8db4-84d635302891",
   ownerId: 123
},
{
   carId: "other_car_id",
   ownerId: 999
}

}

client
  .db("my_db")
  .collection("users")
  .aggregate([
    {
      $lookup: {
        from: "cars",
        localField: "userId",
        foreignField: "ownerId",
        as: "car",
      },
    },
    { $unwind: "$car" },

    {
      $match: {
        $and: [
          { userId: "123" },
          { "car.ownerId": "$userId" },
        ],
      },
    },
  ]);

but doesn't find anything. What I expect is get one document:

{
    userId: "123",
    ...
      car: {
      carId: "3bff06ea-e973-4335-8db4-84d635302891",
      ownerId: 123
   }
},

Could you find a bug in my thinking?

There is 2 problems i think

  • the type of userId is string, and the ownerId is number
  • match can go on top, and only match the userID, lookup will ensure that ownerID will be the same.

*Bellow is a solution with your schema, but i think you should update all documents using a pipeline update and convert userId to number using something like this

users.updateMany({}, [{"$set": {"userId": {"$toInt": "$userId"}}}])

Query

  • like your query but change the type
  • and do the match on top, with only userId

Test code here

users.aggregate(
[{"$match": {"userId": {"$eq": "123"}}},
  {"$set": {"userIdInt": {"$toInt": "$userId"}}},
  {"$lookup": 
    {"from": "cars",
      "localField": "userIdInt",
      "foreignField": "ownerId",
      "as": "car"}},
 {"$unset": ["userIdInt"]},
 {"$unwind": {"path": "$car"}}])

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