我正在努力建立对蒙戈的理解,但许多事情仍然是神秘的。我像这样进行聚合调用:
> db.my_collection_keys.aggregate([ { $project: {value: 1, gaa: {$literal: "baa"}}}])
{ "_id" : "_id", "value" : "dada_id((_id),(_id),(_id),(_id))", "gaa" : "baa" }
{ "_id" : "author", "value" : "(author)", "gaa" : "baa" }
{ "_id" : "available", "value" : "(available)", "gaa" : "baa" }
{ "_id" : "checkout", "value" : "(checkout)", "gaa" : "baa" }
{ "_id" : "language", "value" : "(language)", "gaa" : "baa" }
{ "_id" : "pages", "value" : "(pages)", "gaa" : "baa" }
{ "_id" : "published_date", "value" : "(published_date)", "gaa" : "baa" }
{ "_id" : "publisher_id", "value" : "(publisher_id)", "gaa" : "baa" }
{ "_id" : "title", "value" : "(title)", "gaa" : "baa" }
>
我所看到的看起来非常像我在集合上执行.find()时看到的内容,所以我认为这将是一个集合,但类似
> db.my_collection_keys.aggregate([ { $project: {value: 1, gaa: {$literal: "baa"}}}]).find({$eq: {_id: "author"}})
不起作用。那么究竟是什么返回以及如何使用它呢?
(我知道将输出写入新集合的$ out关键字,但我对操作不太感兴趣,但理解。)
编辑:感谢@JohnnyHK我能够做到以下(作为概念证明):
> var myCursor = db.my_collection_keys.aggregate([ { $project: {value: 1, gaa: {$literal: "baa"}}}])
> while (myCursor.hasNext()) {
x = myCursor.next();
print(tojson(x));
db.dudu.insert(x);
}
... ... ... ... {
"_id" : "_id",
"value" : "dada_id((_id),(_id),(_id),(_id))",
"gaa" : "baa"
}
{ "_id" : "author", "value" : "(author)", "gaa" : "baa" }
{ "_id" : "available", "value" : "(available)", "gaa" : "baa" }
{ "_id" : "checkout", "value" : "(checkout)", "gaa" : "baa" }
{ "_id" : "language", "value" : "(language)", "gaa" : "baa" }
{ "_id" : "pages", "value" : "(pages)", "gaa" : "baa" }
{ "_id" : "published_date", "value" : "(published_date)", "gaa" : "baa" }
{ "_id" : "publisher_id", "value" : "(publisher_id)", "gaa" : "baa" }
{ "_id" : "title", "value" : "(title)", "gaa" : "baa" }
WriteResult({ "nInserted" : 1 })
> db.dudu.find().pretty();
{
"_id" : "_id",
"value" : "dada_id((_id),(_id),(_id),(_id))",
"gaa" : "baa"
}
{ "_id" : "author", "value" : "(author)", "gaa" : "baa" }
{ "_id" : "available", "value" : "(available)", "gaa" : "baa" }
{ "_id" : "checkout", "value" : "(checkout)", "gaa" : "baa" }
{ "_id" : "language", "value" : "(language)", "gaa" : "baa" }
{ "_id" : "pages", "value" : "(pages)", "gaa" : "baa" }
{ "_id" : "published_date", "value" : "(published_date)", "gaa" : "baa" }
{ "_id" : "publisher_id", "value" : "(publisher_id)", "gaa" : "baa" }
{ "_id" : "title", "value" : "(title)", "gaa" : "baa" }
>
将光标的文档放入集合中。 我进一步收集, mongo做事的方式宁愿在聚合管道中添加另一个步骤。
答案 0 :(得分:1)
如the shell docs中所述,aggregate
会返回:
汇总管道操作最后阶段生成的文档的cursor
光标只提供对结果集的访问,并且不可查询。
要在显示时对结果进行后期过滤,您可以在管道中添加$match
阶段:
db.my_collection_keys.aggregate([
{ $project: {value: 1, gaa: {$literal: "baa"}}},
{ $match: {$eq: {_id: "author"}})
]);