我有一个以这种格式存储数据的集合:
{
_id: ObjectId("51b9be6dbbdeef1e5f008cca"),
name: 'sfdsfsdfsdfsdfsd'
details: {
varA: {
created: "2013-06-13T12:43:25.853Z",
validity: "2013-07-13T12:43:25.853Z",
modified: "2013-06-13T12:43:25.853Z"
},
varB: {
created: "2013-06-13T12:43:25.853Z",
validity: "2013-07-13T12:43:25.853Z",
modified: "2013-06-13T12:43:25.853Z"
}
}
}
我希望能够只显示这种格式的varA数据(没有嵌套深度......):
{
_id: ObjectId("51b9be6dbbdeef1e5f008cca"),
name: 'sfdsfsdfsdfsdfsd',
created: "2013-06-13T12:43:25.853Z",
validity: "2013-07-13T12:43:25.853Z",
modified: "2013-06-13T12:43:25.853Z"
}
不幸的是,我的查询(我正在使用投影):
db.coll.find({}, {'details.varB': 0})
返回这样的内容:
{
_id: ObjectId("51b9be6dbbdeef1e5f008cca"),
name: 'sfdsfsdfsdfsdfsd',
details: {
varA: {
created: "2013-06-13T12:43:25.853Z",
validity: "2013-07-13T12:43:25.853Z",
modified: "2013-06-13T12:43:25.853Z"
}
}
如何改进查询查询以返回预期的格式?
非常感谢那些能帮助我的人; - )
P.S。这里我使用mongo shell来检索数据,但我需要使用node-mongodb-native的node.js来处理此查询。
答案 0 :(得分:5)
我只使用聚合函数完成此操作,如我的博文here
中所述对于您的情况,这是有效的
db.temp.aggregate (
{
$project :
{
name:"$name",
created:"$details.varA.created",
validity:"$details.varA.validity",
modified:"$details.varA.modified"
}
}
);
或
db.temp.aggregate ({$project:{name:"$name",created:"$details.varA.created",validity:"$details.varA.validity",modified:"$details.varA.modified"}});
这是样本运行
> db.temp.insert ({name:'sfdsfsdfsdfsdfsd', details: { varA : { created: "2013-06-13T12:43:25.853Z", validity: "2013-07-13T12:43:25.853Z", modified: "2013-06-13T12:43:25.853Z"}, varB : { created: "2013-06-13T12:43:25.853Z", validity: "2013-07-13T12:43:25.853Z", modified: "2013-06-13T12:43:25.853Z" } } })
> db.temp.aggregate ({$project:{name:"$name",created:"$details.varA.created",validity:"$details.varA.validity",modified:"$details.varA.modified"}});
{
"result" : [
{
"_id" : ObjectId("51b9d7151723a9c4d6bc9936"),
"name" : "sfdsfsdfsdfsdfsd",
"created" : "2013-06-13T12:43:25.853Z",
"validity" : "2013-07-13T12:43:25.853Z",
"modified" : "2013-06-13T12:43:25.853Z"
}
],
"ok" : 1
}