[英]Mongo Aggregation/Projection from a subdocument
无法理解查询此mongo文档的具体语法。 我想得到(项目?)只有“条目”,其中u =“123”。 我试过这样的事情:
db["conv_msgs_822"].aggregate({$match: {"_id": "1234", "entries.$.u" : "123"}})
哪个失败了。 这甚至可能吗?
{
"_id" : "1234",
"entries" : {
"1" : {
"body" : "aesf asdf asdf asdf asdf",
"u" : "123"
},
"2" : {
"body" : "1234",
"u" : ""
},
"3" : {
"body" : "some other body ",
"u" : "14"
},
"4" : {
"body" : "another body",
"u" : "123"
}
}
}
您当前的文档结构无法实现这一点。 你真的需要这些子文档在一个数组中做这样的事情。
让我们假设您重新构建文档以匹配此(如果需要在子文档中,您甚至可以将索引添加回字段):
{
"_id" : "1234",
"entries" : [
{
"body" : "aesf asdf asdf asdf asdf",
"u" : "123"
},
{
"body" : "1234",
"u" : ""
},
{
"body" : "some other body ",
"u" : "14"
},
{
"body" : "another body",
"u" : "123"
}
]
}
然后,您可以使用带有$
运算符的基本查询作为投影,以仅匹配第一个项目。
> db.conv_msgs_822.find({"_id": "1234", "entries.u": "123"}, {"entries.$": 1})
哪个会产生:
{ "_id" : "1234", "entries" : [ { "body" : "aesf asdf asdf asdf asdf", "u" : "123" } ] }
为了匹配你需要聚合的所有项目和$unwind
它们$match
子元素并将它们$group
。
db.conv_msgs_822.aggregate(
{$match: {"_id": "1234", "entries.u": "123"}},
{$unwind: "$entries"},
{$match: {"entries.u": "123"}},
{$group: {_id: "$_id", entries: {$push: "$entries"}}}
)
导致:
{
"result" : [
{
"_id" : "1234",
"entries" : [
{
"body" : "aesf asdf asdf asdf asdf",
"u" : "123"
},
{
"body" : "another body",
"u" : "123"
}
]
}
],
"ok" : 1
}
我希望有所帮助。
到目前为止,对我来说最好的潜力是:
db.eval( function(doc, u_val) {
var msgs = doc["entries"];
var cleaned_entries = {};
for (var k in entries){
if (msgs[k].u == u_val){
cleaned_entries[k] = entries[k];
}
};
doc["entries"] = cleaned_entries
return doc
},
db["conv_msgs_822"].findOne({"_id": "1234"}), 123 );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.