Reputation: 83
I am working with MongoDB and I have a question:
Account: {
_id: new ObjectId("<ID>"),
name: "<NAME>"
}
User {
_id: new ObjectId("<ID>"),
email: "<EMAIL>",
password: "<PASSWORD>",
account: DBRef("accounts", ObjectId("<ID>"))
}
How can I look for users with and specific account name?
I tried:
db.users.find({"account.$name": "<NAME>"});
But it does not work.
How can I do it? Is it a good practice?
I appreciate any help.
Thanks in advance.
Upvotes: 1
Views: 28
Reputation: 7578
"Back into it" with $lookup
. First find the name you seek, then $lookup
into the users
collection. Simplfying here:
var r = [
{ id: "A", name: "buzz"}
,{ id: "B", name: "NOTbuzz"}
];
db.acct.drop();
db.acct.insert(r);
var r2 = [
{ email: "[email protected]", account: "A"}
,{ email: "[email protected]", account: "B"}
];
db.users.drop();
db.users.insert(r2);
db.acct.aggregate([
{$match: {"name": "buzz"}}
,{$lookup: { from: "users", localField: "id", foreignField: "account", as: "X"}}
]);
{
"_id" : ObjectId("5a12007bfee383d2d2e74651"),
"id" : "A",
"name" : "buzz",
"X" : [
{
"_id" : ObjectId("5a12007bfee383d2d2e74653"),
"email" : "[email protected]",
"account" : "A"
}
]
}
Upvotes: 1