MongoDB查询列表中的对象属性

时间:2011-12-17 15:28:21

标签: json mongodb querying

假设我有一个这样的文件:

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

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

2 个答案:

答案 0 :(得分:11)

类似的东西:

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

没有经过测试,但你明白了;你可以深入研究这些项目。

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

答案 1 :(得分:6)

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

类似的东西:

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

有关详细信息,请参阅here

相关问题