这是我的完整文档,我只需要它的子块' One'或者'两个'一次。
{
"_id": ObjectId('12abc'),
"createdAt": ISODate('2016-04-04T06:04:53.486Z'),
"updatedAt": ISODate('2016-04-04T06:04:53.486Z'),
"updatedBy": "SSE",
"DocName": "doc1",
"MainObj": {
"One": {
"color": {
"green": [
{
"val": "01",
"val2": "0"
},
{
"val": "10",
"val2": "5"
}
],
"result": "0000"
}
}
"Two": {
"color1": {
"blue": [
{
"val": "01",
"val2": "0"
},
{
"val": "10",
"val2": "5"
}
],
"result": "0000"
}
}
}
}
这是我预期的阻止: 一个":{ " color":{ "绿色":[ { " val":" 01", " val2":" 0" }, { " val":" 10", " val2":" 5" } ] "结果":" 0000" } } }
答案 0 :(得分:0)
您可以通过将子文档(MainObj.One
)投影到名为One的变量中然后仅返回该变量来使用聚合框架执行此操作。例如:
db.YourCollectionName.aggregate([
{$project:{One:"$MainObj.One"}},
{$project:{_id:0,One:1}}
]);
返回:
{ "One" : { "color" : { "green" : [ { "val" : "01", "val2" : "0" }, { "val" : "10", "val2" : "5" } ], "result" : "0000" } } }
有关聚合框架和$project
运算符的更多信息:
https://docs.mongodb.org/manual/reference/operator/aggregation/
更新:以下是包含createdAt,updatedAt,updatedBy和DocName的代码:
db.YourCollectionName.aggregate([
{$project:{One:"$MainObj.One",createdAt:"$createdAt",updatedAt:"$updatedAt",updatedBy:"$updatedBy",DocName:"$DocName"}},
{$project:{_id:0,One:1,createdAt:1,updatedAt:1,updatedBy:1,DocName:1}}
]);
返回:
{
"createdAt" : ISODate("2016-04-04T06:04:53.486Z"),
"updatedAt" : ISODate("2016-04-04T06:04:53.486Z"),
"updatedBy" : "SSE",
"DocName" : "doc1",
"One" : {
"color" : {
"green" : [ { "val" : "01", "val2" : "0" }, { "val" : "10", "val2" : "5" } ],
"result" : "0000"
}
}
}
注意:更简单的方法如下:
db.YourCollectionName.find({},{createdAt:1,updatedAt:1,updatedBy:1,DocName:1,"MainObj.One":1});
唯一的区别是,这会将One
作为MainObj
的子文档返回(与原始问题中的内容不同):
{
"createdAt" : ISODate("2016-04-04T06:04:53.486Z"),
"updatedAt" : ISODate("2016-04-04T06:04:53.486Z"),
"updatedBy" : "SSE",
"DocName" : "doc1",
"MainObj" : {
"One" : {
"color" : {
"green" : [ { "val" : "01", "val2" : "0" }, { "val" : "10", "val2" : "5" } ],
"result" : "0000"
}
}
}
}