1

我在 mongoDB 中有以下名为“CanvasCollection”的集合,我想从该集合中的数组中获取 ID 为“50e6fcc2edcbc10613000022”的图像对象:

{
"_id": ObjectId("50d1f440471ca84e1f000007"),
"image": [{
    "_id": ObjectId("50e6fcc2edcbc10613000022"),
    "type": "image",
    "filename": "50e6fcc2edcbc10613000022.jpg",
    "origname": "2811879134_7a57d7c586_m.jpg",
    "filepath": "upload/50e6fcc2edcbc10613000022.jpg",
    "thumbpath": "upload/50e6fcc2edcbc10613000022_small.jpg",)
}],
"text": [{
    "_id": ObjectId("50e6eda0edcbc1061300001b"),
    "content": "Type your text here"
}]
}

这似乎不起作用:

CanvasCollection.find({'_id': new BSON.ObjectID('50d1f440471ca84e1f000007')}, {'image' : {$elemMatch: {'_id': new BSON.ObjectID('50e6fcc2edcbc10613000022')}}})

任何想法如何得到这个:

{
    "_id": ObjectId("50e6fcc2edcbc10613000022"),
    "type": "image",
    "filename": "50e6fcc2edcbc10613000022.jpg",
    "origname": "2811879134_7a57d7c586_m.jpg",
    "filepath": "upload/50e6fcc2edcbc10613000022.jpg",
    "thumbpath": "upload/50e6fcc2edcbc10613000022_small.jpg",)
}
4

1 回答 1

0

如果你有 MongoDb 2.2 版,你可以这样做:

db.CanvasCollection.aggregate({$project: {image:1}},{ $unwind : "$image" },{ $match : {"image._id": ObjectId("50e6fcc2edcbc10613000022")}})

(这是来自 mongo shell),输出将是这样的:

{
"result" : [
    {
        "_id" : ObjectId("50d1f440471ca84e1f000007"),
        "image" : {
            "_id" : ObjectId("50e6fcc2edcbc10613000022"),
            "type": "image",
            "filename": "50e6fcc2edcbc10613000022.jpg",
            "origname": "2811879134_7a57d7c586_m.jpg",
            "filepath": "upload/50e6fcc2edcbc10613000022.jpg",
            "thumbpath": "upload/50e6fcc2edcbc10613000022_small.jpg"
        }
    }
],
"ok" : 1
}

关于展开:http ://docs.mongodb.org/manual/reference/aggregation/unwind/ 。

类似主题:仅检索 MongoDB 集合中对象数组中的查询元素..

如果您有较旧的 MongoDb 版本,我认为这是不可能的。

于 2013-01-05T00:24:02.263 回答