我的mongodb找到代码:
db.mycollection.runCommand( "text", { search: "yardim", limit:5})
聚合命令:
db.mycollection.aggregate(
{$match:{"source" : {$exists:true}}},
{$group:{_id:"$source", "count": {$sum:1}}}
);
如何将“聚合”代码集成到“查找”代码
答案 0 :(得分:0)
MongoDB的一个乐趣就是它与你的编程语言配合得很好! 因此,我鼓励您记住并(重新)将您的编程语言视为实施解决方案的主要工具。 我轻轻地建议你做“明显的”,收集你的数据库操作的结果,并插入你想要的。 这应该是您的第一个解决方案。 希望它能为您带来足够好的表现,因为它也是目前唯一的解决方案 (好吧,mapReduce可以合并,但它会强制将其结果的形状合并到合并中)。 用于聚合的$ out运算符(从版本2.5.2开始提供)不是合并的解决方案。 在将结果写入值指定的集合时,您无法合并回同一个集合。 如果集合已存在,则旧的现有集合将替换为集合的新结果。
这是一个示例,希望能够很好地说明使用编程语言解决问题的难易程度。
聚集物insert.js
db.mycollection.drop();
db.mycollection.ensureIndex({ quote: "text", source: "text" });
var docs = [
{quote: "Glory is fleeting, but obscurity is forever.", source: "Napoleon Bonaparte"},
{quote: "Political correctness is tyranny with manners.", source: "Charlton Heston"},
{quote: "Not everything that can be counted counts, and not everything that counts can be counted.", source: "Albert Einstein"},
{quote: "Only two things are infinite, the universe and human stupidity, and I'm not sure about the former.", source: "Albert Einstein"},
{quote: "In theory, there is no difference between theory and practice. But in practice, there is.", source: "Yogi Berra"},
{quote: "I find that the harder I work, the more luck I seem to have.", source: "Thomas Jefferson"},
{quote: "Never interrupt your enemy when he is making a mistake.", source: "Napoleon Bonaparte"},
{quote: "The significant problems we face cannot be solved at the same level of thinking we were at when we created them.", source: "Albert Einstein"},
];
db.mycollection.insert(docs);
var aggregation = db.mycollection.aggregate(
{$match: {source: {$exists: true}}},
{$group: {_id: "$source", count: {$sum: 1}}},
{$project: {_id: 0, source: "$_id", count: "$count"}}
);
db.mycollection.insert(aggregation.toArray());
var text_search = db.mycollection.runCommand( "text", { search: "Thomas", limit:5});
printjson(text_search.results);
$ mongo aggregate-insert.js
MongoDB shell version: 2.5.4-pre-
connecting to: test
[
{
"score" : 0.75,
"obj" : {
"_id" : ObjectId("528e3250ac6deb4e169c900e"),
"quote" : "I find that the harder I work, the more luck I seem to have.",
"source" : "Thomas Jefferson"
}
},
{
"score" : 0.75,
"obj" : {
"_id" : ObjectId("528e32504294d7fa2eedec1d"),
"count" : 1,
"source" : "Thomas Jefferson"
}
}
]