Mon go DB сложный запрос - PullRequest
0 голосов
/ 07 февраля 2020

Мне нужна помощь с MongoDB. У меня есть бывшая схема и база данных, как показано ниже: `

Tb:

User:
{
name: { type: String }
image: { type: String }
city: { type: String }
address: [{
    index: { type: Number }
    district_id: { type: Schema.ObjectId, ref: 'District' }
  }]
}

Tb2:

District:{
name: { type: String }
code: { type: String }}

Пример базы данных:

User: [{
    _id: '1234'
    name: 'Jacky',
    image: '',
    city: 'Da Nang',
    address: [
        {
            index: 1,
            district_id: '12345'
        },
        {
            index: 2,
            district_id: '123456'
        },
        {
            index: 3,
            district_id: '1234567'
        }
    ]
}]
District: [
    {
        _id: '12345',
        name: 'Hai Chau',
        code: 12
    },
    {
        _id: '123455',
        name: 'Lien CHieu',
        code: 13
    },
    {
        _id: '1234567',
        name: 'Cam Le',
        code: 14
    },
    {
        _id: '12345678',
        name: 'Son Tra',
        code: 15
    }
]

Как я могу выбрать пользователя с помощью двух из двух вариантов (disctrict.name && index), например: district.name = 'Lien Chieu' && address.index> 1.

1 Ответ

0 голосов
/ 07 февраля 2020

Вы можете попробовать этот запрос ниже:

db.District.aggregate([
    /** filter required doc from district Coll */
    { $match: { name: "Lien CHieu" } },
    {
        $lookup: {
            from: "User",
            let: { id: "$_id" },
            pipeline: [
                /** Basic filter to get matched doc from User Coll */
                { $match: { $expr: { $in: ["$$id", "$address.district_id"] } } },
                /** check for criteria */
                {
                    $addFields: {
                        mappingField: {
                            $map: {
                                input: "$address", as: "each", in: {
                                    $and: [{ $gt: ["$$each.index", 1] }, { $eq: ["$$id", "$$each.district_id"] }]
                                }
                            }
                        }
                    }
                },
                /** filter required doc from above which matches our criteria & remove added field */
                { $match: { mappingField: true } }, { $project: { mappingField: 0 } }
            ],
            as: "userdata"
        }
    }
])

Тест: MongoDB-Playground

...