【问题标题】:How to find a document by its position/index in the array?如何通过其在数组中的位置/索引来查找文档?
【发布时间】:2017-06-24 21:53:22
【问题描述】:

我需要使用 Mongoose 检索 MongoDB 数据库中位置 1,5 和 8 的文档。 是否有可能通过文档在集合中的位置来获取文档?如果是这样,你能告诉我怎么做吗?

我需要这样的东西:

var someDocs = MyModel.find({<collectionIndex>: [1, 5, 8]}, function(err, docs) {

    //do something with the three documents

})

我尝试执行以下操作以查看集合中使用了哪些索引,但我收到“getIndexes 不是函数”错误:

var indexes = MyModel.getIndexes();

感谢任何帮助。

【问题讨论】:

    标签: node.js mongodb mongoose mongodb-query mongoose-schema


    【解决方案1】:

    如果以位置 5 为例,您的意思是集合中的第 5 个字面元素,这不是最好的方法。 Mongo 集合通常按照插入元素的顺序排列,但可能并不总是如此。在此处查看答案并查看natural order:https://stackoverflow.com/a/33018164/7531267 上的文档。

    在您的情况下,您可能在可以查询的每条记录上都有一个唯一的 id。 假设您提到的 [1, 5, 8] 是ids,应该这样做:

    var someDocs = MyModel.find({ $or: [{ id: 1 }, { id: 5 }, { id: 8 }]}}, function(err, cb) {
        //do something with the three documents
    })
    

    您还可以阅读 $in 来替换 $or 并稍微清理一下查询。

    【讨论】:

    • 问题是我需要使用 Mongoose 从集合中获取 3 个随机文档。所以,我想做的方式是生成 3 个随机数并使用这些数字作为集合中的索引来获取文档。所以,如果我的函数生成数字 1、5 和 8,我想使用这些数字。我知道有一个 mongo 函数可以获取随机文档,但需要在 mongoose 中进行。
    • 啊,非常有趣的问题。可能像this 这样的东西可能会有所帮助。要点是:Model.findOne().skip(random),尽管您需要三个查询才能获得三个随机记录。
    【解决方案2】:

    假设您在用户集合中有此文档:

    {
      _id: ObjectId('...'),
      name: 'wrq',
      friends: ['A', 'B', 'C']
    }
    

    下面的代码用于搜索用户'wrq'的第一和第三个朋友:

    db.users.aggregate(
      [
        {
          $match: {
            name: 'wrq'
          }
        },
        {
          $project:{
            friend1: {
              $arrayElemAt: ["$friends", 0]
            },
            friend3: {
              $arrayElemAt: ["$friends", 2]
            }
          }
        }
      ]
    )
    

    【讨论】:

    • 这段代码在 mongo shell 上运行良好,你可能需要通过 mongoose 找到如何做。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多