如何仅使用MongoDB聚合获取数组中的值?
让我们创建一个包含文档的集合-
> db.demo411.insertOne(
... {
... "Information" : [
... {
... "Name1" : "Chris",
... "Name2" : "David"
... },
... {
... "Name1" : "John",
... "Name2" : "John"
... }
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e70f19715dc524f70227682")
}在find()方法的帮助下显示集合中的所有文档-
> db.demo411.find();
这将产生以下输出-
{ "_id" : ObjectId("5e70f19715dc524f70227682"), "Information" : [ { "Name1" : "Chris", "Name2" : "David" }, { "Name1" : "John", "Name2" : "John" } ] }以下是仅获取数组中值的查询-
> db.demo411.aggregate(
... [
... {$project : {
... _id : 0,
... Information : {$map : {input : "$Information", as : "out", in : ["$$out.Name1", "$$out.Name2"]}}
... }
... }
... ]
... )这将产生以下输出-
{ "Information" : [ [ "Chris", "David" ], [ "John", "John" ] ] }热门推荐
10 满月100天简短祝福语
11 节日祝福语幽默简短的
12 三十三句祝福语简短
13 奶奶八十寿辰祝福语简短
14 俄语祝福语贺卡文案简短
15 别人生辰祝福语简短
16 唯美的祝福语简短的
17 国庆中秋祝福语简短搞笑
18 我想找祝福语大全简短