MongoDB-如何根据数组中的第一个元素提取记录

问题描述 投票:2回答:3

以下为附件文件中的2个文档。我需要根据过滤器提取标题字段(Harrison Ford是actor字段中的第一个元素)。所以我需要拉第二份文件。感谢您的帮助。

{
        "_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
3个回答
0
投票

db.collectionName.update({name:'documentName'}, {$pull:{actors:'Jonathan Frakes'}});

这将从您的documentName中的actors数组中删除String Jonathan Frakes


0
投票

所以您想获得以Harrison Ford作为第一演员的电影的名称吗?如果是这样,请尝试一下:

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

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

btw,当您说pull时,可能会让人感到困惑,因为mongodb中有一个$pull运算符。


0
投票
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/

© www.soinside.com 2019 - 2024. All rights reserved.