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
*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
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.