Using MongoDB's positional operator $ in a deeply nested document query

后端 未结 1 1382
一向
一向 2021-01-12 02:58

Is it possible to use positional operator \'$\' in combination with a query on a deeply-nested document array?

Consider the following nested document defining a \'us

1条回答
  •  抹茶落季
    2021-01-12 03:01

    You get an error from

    db.users.findOne(
        { username: 'test', 'kingdoms.buildings.type': 'castle' },
        { kingdoms: {$slice: [n, 1]}, 'kingdom.buildings.$': 1 }
    );
    

    because there is a spelling mistake ("kingdom.buildings.$" should be "kingdoms.buildings.$").
    However, this way can not accomplish what you expect.
    $ is always aimed at kingdoms in the path of kingdoms.buildings - the first array.

    This is a way that should be able to solve the problem.
    (V2.6+ required)

    db.c.aggregate([ {
        $match : {
            username : 'test',
            'kingdoms.buildings.type' : 'castle'
        }
    }, {
        $project : {
            _id : 0,
            kingdoms : 1
        }
    }, {
        $redact : {
            $cond : {
                "if" : {
                    $or : [ {
                        $gt : [ "$kingdoms", [] ]
                    }, {
                        $gt : [ "$buildings", [] ]
                    }, {
                        $eq : [ "$type", "castle" ]
                    } ]
                },
                "then" : "$$DESCEND",
                "else" : "$$PRUNE"
            }
        }
    } ]).pretty();
    

    To only reserve the first element of kingdoms,

    db.c.aggregate([ {
        $match : {
            username : 'test',
            'kingdoms.buildings.type' : 'castle'
        }
    }, {
        $redact : {
            $cond : {
                "if" : {
                    $or : [ {
                        $gt : [ "$kingdoms", [] ]
                    }, {
                        $gt : [ "$buildings", [] ]
                    }, {
                        $eq : [ "$type", "castle" ]
                    } ]
                },
                "then" : "$$DESCEND",
                "else" : "$$PRUNE"
            }
        }
    }, {
        $unwind : "$kingdoms"
    }, {
        $group : {
            _id : "$_id",
            kingdom : {
                $first : "$kingdoms"
            }
        }
    }, {
        $group : {
            _id : "$_id",
            kingdoms : {
                $push : "$kingdom"
            }
        }
    }, {
        $project : {
            _id : 0,
            kingdoms : 1
        }
    } ]).pretty();
    

    0 讨论(0)
提交回复
热议问题