【问题标题】:mongoDB search querymongoDB 搜索查询
【发布时间】:2018-04-22 00:57:28
【问题描述】:

对于一个作业,我们得到以下代码:

db.bib.insertMany( [
      {type : "book",
         "@year": "1994",
         "title": "TCP/IP Illustrated",
         "author": {
            "last": "Stevens",
            "first": "W."
         },
         "publisher": "Addison-Wesley",
         "price": "65"
      },
      {type : "book",
         "@year": "1992",
         "title": "Unix Programming",
         "author": {
            "last": "Stevens",
            "first": "W."
         },
         "publisher": "Addison-Wesley",
         "price": "65"
      },
      {type : "book",
         "@year": "2000",
         "title": "Data on the Web",
         "author": [
            {
               "last": "Abiteboul",
               "first": "Serge"
            },
            {
               "last": "Buneman",
               "first": "Peter"
            },
            {
               "last": "Suciu",
               "first": "Dan"
            }
         ],
         "publisher": "Morgan Kaufmann",
         "price": "39"
      },
      {type : "book",
         "@year": "1999",
         "title": "Digital TV",
         "editor": {
            "last": "Gerbarg",
            "first": "Darcy",
            "affiliation": "CITI"
         },
         "publisher": "Kluwer",
         "price": "130"
      }
    ,
      {type : "journal",
      "title": "Irreproducible results",
      "editor": {
         "last": "Self",
         "first": "W."
      },
      "publisher": "SV"
   }
])

使用 mongoDB,我们被要求完成不同的搜索查询以找到所需的信息。我目前坚持的一个是

列出 1995 年以后出版且价格低于 100 的书籍的书名。

据我了解,正确的查询应该类似于

db.bib.find({price: {$lt: 100}, year: {$gt: 1995}}, {title: 1, _id: 0})

但是,这会在不应该的情况下提供空白结果。为什么会这样,我该如何解决?

【问题讨论】:

  • “对于一个作业,我们得到以下代码...” - 所以我猜你的导师实际上是想让你自己解决这个问题,而不是在 Stack Overflow 上众包.再看看你的领域。在我看来,它们就像“字符串”。
  • @NeilLunn 我确实尝试过自己解决这个问题,因此我提供了一个我前进方向的示例。不管在数字周围加上引号,它仍然不起作用
  • 100 != "100" 还有"65" < "100" == false。解决这些问题。
  • 啊..好吧..我明白你在说什么。但是,我无法更改字段中的数字作为字符串放置。
  • 不能吗?或者也许这就是你应该解决的细节!人们有时会在这种情况下向你“教”一些东西。

标签: mongodb mongodb-query


【解决方案1】:

这两个字段的数据类型都是字符串。您不能将它们作为数字进行比较。尝试以下,它将起作用。使用排序规则,您可以要求 MongoDB 将它们视为 int。你可以阅读更多关于排序规则here at mongodb.com

db.bib.find({$and: [{"@year": {$gt: "1995"}}, {price: {$lt: "100"}}]}).collation({
  locale: "en_US",
  numericOrdering: true
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-19
    • 2022-10-05
    • 2021-12-19
    • 2015-06-29
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多