【问题标题】:Mongoose - How do i find in a collection from an array of object idsMongoose - 我如何从一组对象 id 中找到集合
【发布时间】:2020-05-07 02:19:57
【问题描述】:

假设我有一个对象 ID 数组:

[ 1, 2, 3, 4, 5 ]

我有一个名为 user 的集合,其中包含以下值:

[
  {
     _id: 3,
     name: 'hehe'
  },

  {
     _id: 5,
     name: 'hehe1'
  },

  {
     _id: 2,
     name: 'hehe2'
  },

  {
     _id: 1,
     name: 'hehe3'
  },

  {
     _id: 4,
     name: 'hehe4'
  },

  {
     _id: 6,
     name: 'hehe5'
  }
]

如何向集合“用户”查询数组对象 ID? 结果应该与对象ID数组的顺序相同,这可能吗?

提前致谢!

【问题讨论】:

标签: node.js mongodb mongoose


【解决方案1】:

要获取Id数组的文档可以使用$in如下

collection.find( { key: { $in: [array] }}, callback );

注意:

不建议使用文档的顺序来做一些逻辑。我们不能指望订单总是一样的。

【讨论】:

    【解决方案2】:

    您可以使用$in 过滤文档,然后您可以使用$indexOfArray 添加特殊字段,可以用作$sort 的键:

    db.collection.aggregate([
        {
            $match: { _id: { $in: [ 1, 2, 3, 4, 5 ] } }
        },
        {
            $addFields: { idx: { $indexOfArray: [ [ 1, 2, 3, 4, 5 ], "$_id" ] } }
        },
        {
            $sort: { idx: 1 }
        }
    ])
    

    Mongo Playground

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-03
      • 2020-10-24
      • 2016-06-16
      • 2021-10-23
      • 2019-02-07
      • 2017-09-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多