【问题标题】:Get a value from a MongoDB document从 MongoDB 文档中获取值
【发布时间】:2017-03-09 01:06:19
【问题描述】:

我有一个集合,其中文档如下(MongoDB):

{
    _id: 'ABPS1001',
    Brand: 'DecNag',
    serial: '2393-829-109',
    resume: [
        {
            status: '1',
            nameAg: 'Gina',
            lastNameAg: 'Saenz',
            coord_id: '1025',
            movDate: '25-10-2016 11:33'
        },
        {
            status: '0',
            techID: '11',
            coord_id: '1025',
            movDate: '30-10-2016 16:29',
            idReplace: 'ABPS1026'
        },
        {
            status: '1',
            nameAg: 'Diana',
            lastNameAg: 'Gutierrez',
            coord_id: '1014',
            techID: '10',
            movDate: '04-11-2016 09:12'
        },
        {
            status: '0',
            techID: '12',
            coord_id: '1014',
            movDate: '30-11-2016 16:25',
            idReplace: 'ABPS1021'
        },
        {
            status: '1',
            nameAg: 'Laura',
            lastNameAg: 'Diaz',
            coord_id: '1012',
            techID: '11',
            movDate: '04-12-2016 11:33'
        },
        {
            status: '0',
            techID: '10',
            coord_id: '1012',
            movDate: '22-12-2016 12:21',
            idReplace: 'ABPS1107'
        },
        {
            status: '1',
            nameAg: '172.27.48.125',
            lastNameAg: '',
            coord_id: '1004',
            techID: '12',
            movDate: '27-12-2016 08:30'
        },
        {
            status: '0',
            techID: '11',
            movDate: '02-02-2017 14:12',
            idReplace: 'ABPS1107'
        }
     ]
 }

我需要从 _id: 'ABPS1001' 的文档中获取“简历”处的最后一个条目,而不是整个文档。有没有办法使用 MongoDB 语句而不是使用编程语言进行处理?

另外,如何将值附加或删除到“resume”上的任何一组值(例如,如果我想将“coord_id”添加到“resume”上的最后一组)?

谢谢!

【问题讨论】:

  • 在提出这个问题之前,您是否尝试过寻找答案?您的两个问题在 mongo 中都是基本的,您可以很容易地找到解决方法。让我给你一个提示:1. aggregationfilter 。 2.update
  • 是的,我做到了,但使用我发现的信息并不能满足我的需求。无论如何,我会重新检查 MongoDB 文档和 @dyouberg 信息,这非常有帮助。

标签: php mongodb


【解决方案1】:

以下是如何使用聚合来完成问题的第一部分:

// Returns last value of the resume array...
// First - Match the document
// Second - Project to slice the last element of the resume array and put it into a new document called lastValue
db.foo.aggregate([
    { $match: {"_id": "ABPS1001"} }, 
    { $project: { lastValue: { $slice: [ "$resume", -1 ] } } }
])

结果:

{
    "_id" : "ABPS1001",
    "lastValue" : [
        {
            "status" : "0",
            "techID" : "11",
            "movDate" : "02-02-2017 14:12",
            "idReplace" : "ABPS1107"
        }
    ]
}

对于第二部分,您可以使用“$”运算符进行位置更新,see here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-15
    • 2021-08-17
    • 2023-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多