【问题标题】:How to find using json object using mongoose [duplicate]如何使用 mongoose 查找使用 json 对象 [重复]
【发布时间】:2020-03-27 00:17:44
【问题描述】:

我在 mongodb 中有如下数据。

{
   "color":"gray",
   "object": {
       "name": "apple",
       "price": "2000",
       "qu" : "good"
   }
}

我想在 nodejs 中使用 mongoose 来查找这些数据。

  const result  = await findOne({color: "gray", object:{name:"apple"}})

但它什么也没给。如何使用 find well 来查找 json 对象的内部?
非常感谢您阅读它。

【问题讨论】:

  • const result = await findOne({color: "gray", "object.name":"apple" })

标签: node.js mongodb mongoose


【解决方案1】:

你可以使用:

const result = await Model.findOne({color: "gray", "object.name":"apple" });

【讨论】:

    【解决方案2】:
    const result  = await YourSchemaModelName.findOne({
                                                       "color": "gray", 
                                                       "object.name": { "$eq" : "apple"}
                                                      });
    

    【讨论】:

      【解决方案3】:

      使用点符号查找嵌套对象

      const result = await Model.find({ 
          "color": "gray",
          "object.name": "apple"
      })
      .limit(1)
      

      仅供参考:出于性能原因,我使用 .find() + .limit(1) 而不是 .findOne()

      https://dba.stackexchange.com/questions/7573/difference-between-mongodbs-find-and-findone-calls

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-05-13
        • 2018-11-10
        • 1970-01-01
        • 2017-03-30
        • 2020-09-15
        • 2018-02-04
        • 1970-01-01
        • 2017-04-04
        相关资源
        最近更新 更多