【问题标题】:Search for the presence of a string in multiple arrays of a document in mongo db在 mongodb 中搜索文档的多个数组中是否存在字符串
【发布时间】:2020-06-17 19:03:36
【问题描述】:

我想进行一个查询,现在我将在其中提供一个 _id 和国家名称,结果我想找到给定国家/地区是否存在于这三个数组中的真值或假值。如果存在则 true 而不是 false。例如我有 country:France_id:5e4d18bd10e5482eb623c6e4 那么结果将是-

country_array_1:真, country_array_2:真, country_array_3:false

我想要一个 mongo db 查询这种类型的输入和输出我可以聚合或 findOne 但我想要我的答案

 0  _id:5e4d18bd10e5482eb623c6e4
       country_array_1:['France','Italy','China'],
       country_array_2:['Finland','England','France']
       country_array_3:['USA','turkey','India']

 1  _id:5e4345bd10e5482eb62E4X11f
       country_array_1:['Srilanka','Malaysia','Pakistan'],
       country_array_2:['Egypt','Austria','Netherland']
       country_array_3:['Mexico','turkey','India']

我想进行一个查询,我将在其中输入

[Input]
 _id:5e4d18bd10e5482eb623c6e4,
 country:'France'

[Output]
 country_array_1:true,
 country_array_2:true,
 country_array_3:false

【问题讨论】:

  • 看看mongo聚合管道,你肯定可以做到的。
  • 我已经查看并尝试过,但我没有得到准确的答案,是的,您是正确的,答案将通过聚合来实现,但是如何?

标签: node.js mongodb mongoose mongoose-schema


【解决方案1】:

聚合管道

db.test.aggregate([
  { $match: { _id: ObjectId("5e4d18bd10e5482eb623c6e4") } },
  {
    $project: {
      country_array_1: {
        $in: ["France", "$country_array_1"]
      },
      country_array_2: {
        $in: ["France", "$country_array_2"]
      },
      country_array_3: {
        $in: ["France", "$country_array_3"]
      }
    }
  }
]);

输出:

{
    "_id" : ObjectId("5e4d18bd10e5482eb623c6e4"),
    "country_array_1" : false,
    "country_array_2" : true,
    "country_array_3" : false
}

【讨论】:

  • 它会返回布尔结果吗?
  • 是的,试试看
  • MongoError: $in 需要一个数组作为第二个参数,发现:missing I got this error
  • 谢谢pavan,我试了几次,在一些错误之后它成功了。谢谢你的帮助
猜你喜欢
  • 1970-01-01
  • 2020-07-24
  • 2021-05-16
  • 1970-01-01
  • 1970-01-01
  • 2019-08-03
  • 2014-10-26
  • 1970-01-01
  • 2021-03-26
相关资源
最近更新 更多