简体   繁体   中英

In MongoDB, how can I find documents whose id are in a array field of other documents?

I have these documents in the collection "banks". The "accounts" array store the ID's of the accounts linked to each bank.

/* 1 */
{
    "_id" : "1",
    "city" : "Madrid",
    "accounts" : [ 
        "1", 
        "2", 
        "3", 
        "4", 
        "5", 
        "6"
    ]
}

/* 2 */
{
    "_id" : "2",
    "city" : "Berlin",
    "accounts" : [ 
        "7", 
        "8"
    ]
}

/* 3 */
{
    "_id" : "3",
    "city" : "Madrid",
    "accounts" : [ 
        "9", 
        "10", 
        "11", 
        "12"
    ]
}

And collection "accounts" goes like this:

/* 1 */
{
    "_id" : "1",
    "owner" : "Antonio"
}

/* 2 */
{
    "_id" : "2",
    "owner" : "Pedro"
}

/* etc, up to 12 accounts */

I want to find all the accounts that are in any bank located in "Madrid" (I should get all accounts but 7 and 8) I believe the first step is to create an array of the banks located in Madrid like this:

banksInMadrid = db.banks.find({ city: "Madrid"}).toArray()

But I have no clue on what to do next.

Thank you.

Edit: I'm using MongoDB 3.2

Whenever we need data from two or more collections we perform $lookup inside an aggregation pipeline. Read this doc and try this:

db.accounts.aggregate([
    {
        $lookup: {
            from: "banks",
            localField: "_id",
            foreignField: "accounts",
            as: "banks"
        }
    },
    { $unwind: "$banks" },
    {
        $match: { "banks.city": "Madrid" }
    },
    {
        $project: { banks: 0 }
    }
]);

output:

/* 1 */
{
    "_id" : "1",
    "owner" : "Antonio"
},

/* 2 */
{
    "_id" : "2",
    "owner" : "Pedro"
}

You can use find into sub documents like:

db.banks.find( { "accounts._id": 2 )

Check this for more information: https://docs.mongodb.com/manual/tutorial/query-embedded-documents/

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