找到所有文档的正确语法是什么?在嵌入式文档数组中,用户名为' User1'?
这些变化尚未奏效:
db.collection.find( { to: { username: { $in: [ "User1" ] } } } )
db.collection.find( { to: { $in: [ { username: "User1" } ] } } )
文档看起来像:
{
"message" : "Here's a Message",
"to" : [
{
"user" : ObjectId("53aada6f8b10eb0000ec8a90"),
"username" : "User1",
"updated" : ISODate("2014-06-28T19:14:20Z"),
"_id" : ObjectId("53af140c14809099b615d347"),
"read" : {
"marked" : false
}
}
{
"user" : ObjectId("53aada6f8b10eb0000ec8a91"),
"username" : "User2",
"updated" : ISODate("2014-06-28T19:15:20Z"),
"_id" : ObjectId("53af140c14809099b615d348"),
"read" : {
"marked" : false
}
}
]
}
答案 0 :(得分:1)
您想使用dot notation来访问数组的元素。正确的语法是:
db.collection.find({"to.username": { $in: ["User1"] }});
当您要查找多个值时,会使用$in运算符。 如果您只使用一个值进行搜索,则更有效的查询是简单的相等检查:
db.collection.find({"to.username": "User1"});