我有以下架构:
{
"_id" : "1128",
"revisions" : {
"1" : {
"message": "Hi I am revision1!!",
"timestamp" : NumberLong(1462477684),
"userId" : NumberLong(3)
},
"2" : {
"message": "Hi I am revision2!!",
"timestamp" : NumberLong(1462477777),
"userId" : NumberLong(3)
},
.... // Goes up to 90 for example
}
}
我只需要返回"消息"对于修订[2],语法是什么?
我试过了:
db.test.findOne({"_id":"1128"}, {"revisions": {$slice:[2,1]}});
和
db.test.aggregate([
{$match: {_id:"1128"}},
{$unwind: '$revisions'},
{$match: {'$revisions.$':39}}
]);
感谢。
答案 0 :(得分:1)
您正在使用错误的方法和错误的操作员。
只需使用findOne()
方法并访问" 2"带有dot notation的字段。
db.test.findOne( { "_id": "1128" }, { "revisions.2": 1 } )
产生:
{
"_id" : "1128",
"revisions" : {
"2" : {
"message" : "Hi I am revision2!!",
"timestamp" : NumberLong(1462477777),
"userId" : NumberLong(3)
}
}
}
答案 1 :(得分:0)
我测试了这些
对于id为1的修订
db.getCollection('test').find({"_id":"1128"},{"revisions.1":""})
对于id为2的修订
db.getCollection('test').find({"_id":"1128"},{"revisions.2":""})