mongoose 如何查询子文档数组中的元素

vsdwdz23  于 2022-11-13  发布在  Go
关注(0)|答案(1)|浏览(176)

这是路由模型的 Mongoose 模式

const routeSchema = new mongoose.Schema({
    route: {
        type: [{
            stationCode: {
                type: String,
                required: true,
                uppercase: true,
                validate: {
                    validator: async function(val) {
                        const doc = await Station.findOne({
                            code: val,
                        });
                        if (!doc) return false;
                        return true;
                    },
                    message: `A Station with code {VALUE} not found`,
                },
            },
            distanceFromOrigin: {
                type: Number,
                required: [
                    true,
                    'A station must have distance from origin, 0 for origin',
                ],
            },
        }, ],

        validate: {
            validator: function(val) {
                return val.length >= 2;
            },
            message: 'A Route must have at least two stops',
        },
    },
}, {
    toJSON: {
        virtuals: true
    },
    toObject: {
        virtuals: true
    },
});

该模式有一个字段路由为数组的文档,每个文档有一个stationCode、
我想查询所有包含指定顺序的“KMME”和“ASN”stationCode的文档。

{
    "_id": {
        "$oid": "636957ce994af955df472ebc"
    },
    "route": [{
            "stationCode": "DHN",
            "distanceFromOrigin": 0,
            "_id": {
                "$oid": "636957ce994af955df472ebd"
            }
        },
        {
            "stationCode": "KMME",
            "distanceFromOrigin": 38,
            "_id": {
                "$oid": "636957ce994af955df472ebe"
            }
        },
        {
            "stationCode": "ASN",
            "distanceFromOrigin": 54,
            "_id": {
                "$oid": "636957ce994af955df472ebf"
            }
        }
    ],
    "__v": 0
}

请建议此问题的查询或此问题的其他模式定义

uyhoqukh

uyhoqukh1#

一个简单的选项是:

db.collection.aggregate([
  {$match: {$expr: {$setIsSubset: [["ASN", "KMME"], "$route.stationCode"]}}},
  {$set: {
      wanted: {$first:{
        $filter: {
          input: "$route",
          cond: {$in: ["$$this.stationCode", ["ASN", "KMME"]]}
        }
      }}
  }},
  {$match: {"wanted.stationCode": "KMME"}},
  {$unset: "wanted"}
])

了解它在playground example上的工作原理

相关问题