db.chat.find().pretty().limit(3)
{
"_id" : ObjectId("593921425ccc8150f35e7662"),
"user1" : 1,
"user2" : 2,
"messages" : [
{
"capty" : 'A',
"body" : "hiii 0"
},
{
"capty" : 'B',
"body" : "hiii 1"
},
{
"capty" : 'A',
"body" : "hiii 2"
}
]
}
{
"_id" : ObjectId("593921425ccc8150f35e7663"),
"user1" : 1,
"user2" : 3,
"messages" : [
{
"capty" : 'A',
"body" : "hiii 0"
},
{
"capty" : 'A',
"body" : "hiii 1"
},
{
"capty" : 'B',
"body" : "hiii 23"
}
]
}
{
"_id" : ObjectId("593921425ccc8150f35e7664"),
"user1" : 1,
"user2" : 4,
"messages" : [
{
"capty" : 'A',
"body" : "hiii 0"
},
{
"capty" : 'B',
"body" : "hiii 1"
},
{
"capty" : 'B',
"body" : "hiii 24"
}
]
}
需要查询: 行数“user1”:1,“capty”:“B”和“body”:“hiii 1”
我试过了:
db.chat.aggregate([
{ "$match": { "user1": 1, "messages.capty": "B" , "messages.body": "hiii 1" } }
])
但是这不匹配任何capty ='B'或“messages.body”的消息:“hiii 1”。
即可取的输出。 2(记录1和记录3)
答案 0 :(得分:1)
您需要$elemMatch
。该运算符用于"多个标准"来自数组元素:
db.chat.find({
"user1": 1,
"messages": {
"$elemMatch": { "capty": "B" , "body": "hiii 1" }
}
})
计数:
db.chat.find({
"user1": 1,
"messages": {
"$elemMatch": { "capty": "B" , "body": "hiii 1" }
}
}).count()
这将匹配正确的文件并返回其计数。
返回实际文件:
{
"_id" : ObjectId("593921425ccc8150f35e7662"),
"user1" : 1,
"user2" : 2,
"messages" : [
{
"capty" : "A",
"body" : "hiii 0"
},
{
"capty" : "B",
"body" : "hiii 1"
},
{
"capty" : "A",
"body" : "hiii 2"
}
]
}
{
"_id" : ObjectId("593921425ccc8150f35e7664"),
"user1" : 1,
"user2" : 4,
"messages" : [
{
"capty" : "A",
"body" : "hiii 0"
},
{
"capty" : "B",
"body" : "hiii 1"
},
{
"capty" : "B",
"body" : "hiii 24"
}
]
}
同样的"查询"条件适用于汇总$match
,如果你真的想在那里使用它。但对于" count",使用"光标"会更快。