【问题标题】:MongoDB - how do I pull the record based on the first element in arrayMongoDB - 如何根据数组中的第一个元素提取记录
【发布时间】:2020-03-16 03:53:56
【问题描述】:

这是附件中的 2 个文档。我需要根据过滤器提取标题字段(哈里森福特是演员字段中的第一个元素)。所以我需要拉第二个文件。感谢您的帮助。

{
        "_id" : ObjectId("5e66e96a2f86fd04deaa59c5"),
        "title" : "Star Trek Into Darkness",
        "actors" : [
                "Chris Pine",
                "Zachary Quinto",
                "Harrison Ford",
                "Karl Urban"
        ]
}
{
        "_id" : ObjectId("5e66e96a2f86fd04deaa59c6"),
        "title" : "Raiders of the lost ark",
        "actors" : [
                "Harrison Ford",
                "Jonathan Frakes",
                "Brent Spiner",
                "LeVar Burton"
        ]
}

【问题讨论】:

    标签: arrays mongodb filter element projection


    【解决方案1】:

    所以您想获得以Harrison Ford 作为第一个演员的电影的标题,对吗? 如果是这样,试试这个:

    db.collection.find(
        { 'actors.0': 'Harrison Ford' },
        { title: 1, _id: 0 }
    )
    

    https://mongoplayground.net/p/f4-o13NjYNc

    顺便说一句,当你说 pull 时,它可能会让人们感到困惑,因为 mongodb 中有一个 $pull 运算符。

    【讨论】:

    • 成功了,感谢您的快速回复。我之前在玩 match, elemMatch , projection ,但是没有用,
    【解决方案2】:
    db.collection.update({_id:'Your match id'}, {$pull:{actors:'Jonathan Frakes'}});
    
    you can pull record with $pull and then update that record. Please check below link
    

    https://docs.mongodb.com/manual/reference/operator/update/pull/

    【讨论】:

    • 对不起,我不应该在我的问题中使用 pull。我只是想提取。它的工作不感谢您的回复。
    • 你说你想拉那个记录。 @usal2100
    猜你喜欢
    • 2019-09-25
    • 2021-09-04
    • 1970-01-01
    • 2023-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多