指定 Return 格式
Specify Return Format
在 mongo 中有没有一种方法可以让我指定我想要的数据 returned 的格式?
如果可能的话,我希望能够 return 项目作为数组。让我们看看这个非常基本的例子:
{
color: red
},
{
color: white
},
{
color: blue
}
所以对于这个例子,我想将上述文档作为一个数组获取:
{
colors: [red, white, blue]
}
有什么方法可以指定如何return项?我知道我可以指定要获取的列,但随后我必须遍历它们来构建数组。我希望 mongodb 内置了这个,因为它可能比节点、php、java 等更快地完成它
使用 aggregation framework. The aggregation pipeline would simply have a $group
operation where the $addToSet
运算符将值添加到数组中。例如,一个包含示例文档的集合:
/* 1 */
{
"_id" : ObjectId("553c0101dddf8dcf96bdcdea"),
"color" : "red"
}
/* 2 */
{
"_id" : ObjectId("553c0101dddf8dcf96bdcdeb"),
"color" : "white"
}
/* 3 */
{
"_id" : ObjectId("553c0101dddf8dcf96bdcdec"),
"color" : "blue"
}
以下汇总
db.collection.aggregate([
{
"$group": {
"_id": 0,
"colors": {
"$addToSet": "$color"
}
}
},
{
"$project": {
"_id": 0,
"colors": 1
}
}
])
将产生所需的输出:
/* 1 */
{
"result" : [
{
"colors" : [
"blue",
"white",
"red"
]
}
],
"ok" : 1
}
在 mongo 中有没有一种方法可以让我指定我想要的数据 returned 的格式?
如果可能的话,我希望能够 return 项目作为数组。让我们看看这个非常基本的例子:
{
color: red
},
{
color: white
},
{
color: blue
}
所以对于这个例子,我想将上述文档作为一个数组获取:
{
colors: [red, white, blue]
}
有什么方法可以指定如何return项?我知道我可以指定要获取的列,但随后我必须遍历它们来构建数组。我希望 mongodb 内置了这个,因为它可能比节点、php、java 等更快地完成它
使用 aggregation framework. The aggregation pipeline would simply have a $group
operation where the $addToSet
运算符将值添加到数组中。例如,一个包含示例文档的集合:
/* 1 */
{
"_id" : ObjectId("553c0101dddf8dcf96bdcdea"),
"color" : "red"
}
/* 2 */
{
"_id" : ObjectId("553c0101dddf8dcf96bdcdeb"),
"color" : "white"
}
/* 3 */
{
"_id" : ObjectId("553c0101dddf8dcf96bdcdec"),
"color" : "blue"
}
以下汇总
db.collection.aggregate([
{
"$group": {
"_id": 0,
"colors": {
"$addToSet": "$color"
}
}
},
{
"$project": {
"_id": 0,
"colors": 1
}
}
])
将产生所需的输出:
/* 1 */
{
"result" : [
{
"colors" : [
"blue",
"white",
"red"
]
}
],
"ok" : 1
}