【问题标题】:mongodb $match and $nin with _id [duplicate]带有_id的mongodb $match和$nin [重复]
【发布时间】:2019-07-24 22:51:50
【问题描述】:

我的代码:

questionSchema.statics.getRandomByUser = function getRandomByUser(user) {
  const aggr = [{ $sample: { size: 1 } }];
  console.log(`user.answered = ${user.answered}`);
  if (user.answered.length || user.categories.length) {
    const match = { $match: {} };
    if (user.answered.length) match.$match._id = { $nin: user.answered };
    if (user.categories.length) match.$match.category = { $in: user.categories };
    aggr.unshift(match);
  }

  console.log(`aggr = ${JSON.stringify(aggr)}`);
  return this.model('question').aggregate(aggr);
};

结果聚合为:

[{"$match":{"_id":{"$nin":["5c7bb1d08f999f326151df49","5c7bb1d08f999f326151df49"]},"category":{"$in":["Test"]}}},{"$sample":{"size":1}}]

按类别过滤效果很好。但我的$nin 只是忽略了。我必须如何使用 $nin_id 来忽略不需要的文档?

【问题讨论】:

  • 即使这被标记为[重复],我认为这个问题非常有用,因为它处理 $nin。 $nin 的例子并不多。感谢分享

标签: mongodb mongoose


【解决方案1】:

mongoDb 中的_id 通常是ObjectId,它是一个 24 字符的十六进制唯一键。

可以将字符串_id转成ObjectId再查询

[{"$match":{"_id":{"$nin":[ObjectId("5c7bb1d08f999f326151df49"),ObjectId("5c7bb1d08f999f326151df49")]},"category":{"$in":["Test"]}}},{"$sample":{"size":1}}]

【讨论】:

  • 那么最好的解决方案是什么?将ObjectId 保存在数组中或创建附加索引(就像我现在所做的那样)?
  • @MikitaMelnikau 据我了解,如果您在 user 中的唯一键,即 _id 是一个 ObjectId,您应该在脚本中将您的 id 从字符串转换为 ObjectId。 MongoDb 默认将 _id 设置为 ObjectId,而不是像您查询的那样纯字符串。
  • _id 默认是 mongo 索引。只需确保您的数据类型正确即可。
猜你喜欢
  • 2022-11-30
  • 1970-01-01
  • 2012-04-29
  • 1970-01-01
  • 1970-01-01
  • 2015-04-24
  • 2016-04-20
  • 2015-12-28
  • 1970-01-01
相关资源
最近更新 更多