MongoDB匹配数组中最后一个子文档的某属性

版权声明:未经允许不得转载。 https://blog.csdn.net/qq_35958788/article/details/83340104

说明

示例

插入数据

db.users.insert({"books":[{"name":"spring","author":"manA"},{"name":"summer","author":"manB"},{"name":"autumn","author":"manC"},{"name":"winter","author":"manD"}]})

db.users.insert({"books":[{"name":"spring","author":"manE"},{"name":"summer","author":"manF"},{"name":"autumn","author":"manG"},{"name":"winter","author":"manH"}]})

db.users.insert({"books":[{"name":"spring","author":"manI"},{"name":"summer","author":"manJ"},{"name":"autumn","author":"manK"},{"name":"winter","author":"manL"}]})

检索过滤

  • 语法:{$slice: [startIndex, length]}
db.users.find({},{"books":{$slice:[2,2]}})
  • 结果
{ 
    "_id" : ObjectId("5bcfd2be7d1ec2d48d33f98f"), 
    "books" : [
        {
            "name" : "autumn", 
            "author" : "manC"
        }, 
        {
            "name" : "winter", 
            "author" : "manD"
        }
    ]
}
{ 
    "_id" : ObjectId("5bcfd3f77d1ec2d48d33f990"), 
    "books" : [
        {
            "name" : "autumn", 
            "author" : "manG"
        }, 
        {
            "name" : "winter", 
            "author" : "manH"
        }
    ]
}
{ 
    "_id" : ObjectId("5bcfd4317d1ec2d48d33f991"), 
    "books" : [
        {
            "name" : "autumn", 
            "author" : "manK"
        }, 
        {
            "name" : "winter", 
            "author" : "manL"
        }
    ]
}

聚合过滤(匹配数组中最后一个子文档的某属性)

  • 说明:先过滤,后查询
  • 语法:$slice:["$array", [startIndex, ] length ] (startIndex可以省略,默认从0开始)
  • 属性名 books可以更改,进行输出重命名
db.users.aggregate({$project:{"books":{$slice:["$books", -1]}}},{$match:{"books.author":"manD"}})
  • 结果
{ 
    "_id" : ObjectId("5bcfd2be7d1ec2d48d33f98f"), 
    "books" : [
        {
            "name" : "winter", 
            "author" : "manD"
        }
    ]
}

猜你喜欢

转载自blog.csdn.net/qq_35958788/article/details/83340104