【问题标题】:MongoDB Querying for object property in listMongoDB查询列表中的对象属性
【发布时间】:2012-01-22 15:54:21
【问题描述】:

假设我确实有这样的文档:

{
    _id: "cow",
    comments: [
        {user: "karl", comment: "I like cows.", at: /*a date*/},
        {user: "harry", comment: "Cows are the best.", at: /*a date*/}
    ]
}

现在我想收集"karl" 留在我的数据库中的所有 cmets。或者只是某个日期的那些。 "comments" 已编入索引,如何查询?

【问题讨论】:

    标签: json mongodb querying


    【解决方案1】:

    类似:

    db.foo.find({"comments.user":"karl", "comments.at":{$gt:{dateObject}});
    

    尚未测试,但您明白了;您可以深入了解此类项目。

    我建议您浏览这个网站,因为它会引导您完成大量互动教程:Interactive Tutorial

    【讨论】:

      【解决方案2】:

      您应该使用 $elemMatch 来匹配同一文档中的多个条件。

      类似:

      db.foo.find({comments: {"$elemMatch": {user: "karl", at: {$gt:{dateObject}}}})
      

      更多详情请见here

      【讨论】:

      • mongodb 网站更改了他们的文档网址 - 无论如何,我用新网站上的相关内容更新了我的答案。
      猜你喜欢
      • 2021-11-14
      • 2022-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多