首页 > 解决方案 > Mongo DB 复杂查询

问题描述

我需要一些有关 MongoDB 的帮助。我有 Ex Schema 和 Database 如下:`

结核病:

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

结核病:

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。

标签: mongodbmean-stack

解决方案


您可以尝试以下查询:

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-游乐场


推荐阅读