【问题标题】:Get n-th element of an array in MongoDB在MongoDB中获取数组的第n个元素
【发布时间】:2011-11-05 14:25:00
【问题描述】:

作为 MongoDB 文档的一部分,我存储了一个对象数组。例如,如何仅查询数组的第 4 个元素?所以我不想得到整个数组,只是第 4 个元素。

【问题讨论】:

标签: mongodb mongodb-query aggregation-framework


【解决方案1】:

使用$slice

db.foo.find({ bar : "xyz" } , { my_array : { $slice : [n , 1] } } )

将检索 foo 集合中 bar = "xyz" 中所有文档的数组 "my_array" 的第 n 个元素。

MongoDB 文档中的一些其他示例:

db.posts.find({}, {comments:{$slice: 5}}) // first 5 comments
db.posts.find({}, {comments:{$slice: -5}}) // last 5 comments
db.posts.find({}, {comments:{$slice: [20, 10]}}) // skip 20, limit 10
db.posts.find({}, {comments:{$slice: [-20, 10]}}) // 20 from end, limit 10

你可以在这里阅读:http://www.mongodb.org/display/DOCS/Retrieving+a+Subset+of+Fields

【讨论】:

  • 对您的行进行小修正 " db.foo.find({ bar : "xyz" } , { my_array : { $slice : [n , 1] } } ) 将检索第 n 个元素foo 集合中所有文档的数组“my_array”,其中 bar =“xyz”。“我认为这将给出数组 my_array 中的第 (n+1) 个元素,因为 $slice : [n, 1] 表示跳过 n , limit 1 ,因此它将返回数组中的第 n+1 个元素
【解决方案2】:

另一种方法是使用更新数组语法。这里,contribs.1contribs 数组中的第二个元素设置为具有值ALGOL 58(取自manual page on update syntax

db.bios.update(
   { _id: 1 },
   { $set: { 'contribs.1': 'ALGOL 58' } }
)

【讨论】:

  • 但是我们正在寻找 get 元素,而不是 push 元素:?
  • 由于帖子没有尝试回答原始问题并且没有用处,考虑否决它,以便有机会将其删除。
【解决方案3】:

您可以使用 MongoDB 3.2 中的 $arrayElemAt 运算符 new 来返回指定数组索引处的元素。


演示:

名为 baskets 的集合包含如下所示的文档:

{
    "_id" : ObjectId("578f326f6db61a299a383c5a"),
    "fruits" : [
        "apple",
        "mango",
        "banana",
        "apricot",
        "cherry"
    ]
}

以下查询返回“fruits”数组中索引-2(第二个元素)处的元素。

db.baskets.aggregate(
    [
        { "$project": { "matched": { "$arrayElemAt": [ "$fruits", 1 ] } } } 
    ] 
)

产生

{ 
    "_id" : ObjectId("578f326f6db61a299a383c5a"), 
    "matched" : "mango" 
}

以下查询数组中最后一个元素之前的元素;因此索引处的元素-2

db.baskets.aggregate(
    [
        { "$project": { "matched": { "$arrayElemAt": [ "$fruits", -2 ] } } } 
    ] 
)

产生:

{ 
    "_id" : ObjectId("578f326f6db61a299a383c5a"), 
    "matched" : "apricot" 
}

【讨论】:

    猜你喜欢
    • 2020-07-21
    • 1970-01-01
    • 1970-01-01
    • 2021-10-05
    • 2021-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多