select使用唯一的ID在MongoDB中不工作的数组元素
我的应用程序有“post”,这将有故事
现在,我要select故事数组中多个故事中的一个故事并仅select其中一个故事
var db = req.db; var mongo = require('mongodb'); var collection = db.get('clnPost'); var userId = req.body.userId; var postId = req.body.postId; var storyId = req.body.storyId; var ObjectID = mongo.ObjectID; var mongo = require('mongodb'); var ObjectID = mongo.ObjectID; collection.find({ _id: ObjectId(postId), "Stories._id": ObjectID(req.body.storyId)}, function (e, docs) { //some processing on the docs }
我希望这个返回的post和只包含通过请求发送的故事Id的故事一起,但是它返回了故事数组中的所有故事
在这里,我得到了这个职位的所有故事,因为我只需要与Id相匹配的故事req.body.storyId
我也试过使用$ elemMatch检查这个问题后,但仍然得到了相同的结果
collection.find({ _id: postId}, {Stories: { $elemMatch: { _id: req.body.storyId } } }, function (e, docs) {
我也试过了
collection.find({ "Stories._id":ObjectID(storyId)}, {"Stories.$":1,Stories: {$elemMatch: { "Stories._id" :ObjectID(storyId) }} } , function (e, docs) {
后文件的结构如下
{ "_id": { "$oid": "55a7847ee4b07e03cc6acd21" }, "Stories": [ { "userId": "743439369097985", "story": "some story goes on here", "_id": { "$oid": "55c0b9367d1619a81daaefa0" }, "Views": 29, "Likes": [] }, { "userId": "743439369097985", "story": "some story goes on here", "_id": { "$oid": "55c0bbd97abf0b941aafa169" }, "Views": 23, "Likes": [] } ] }
我也尝试使用$ unwind
var test= collection.aggregate( //where collection =db.get('clnPost') { $match: { "Stories._id": ObjectID(storyId) } }, { $project : { Stories : 1 } }, { $unwind : "$Stories" } );
更新1:我使用和尚,因此聚合不起作用
我不能复制你的示例文件,所以我使用了类似的文件:
{ "_id" : "55a7847ee4b07e03cc6acd21", "Stories" : [{ "userId" : "743439369097985", "story" : "some story goes on here", "_id" : "55c0b9367d1619a81daaefa0", "Views" : 29, "Likes" : [ ] }, { "userId" : "743439369097985", "story" : "some story goes on here", "_id" : "55c0bbd97abf0b941aafa169", "Views" : 23, "Likes" : [ ] }] }
为了得到你想要的,你需要使用美元投影算子 ,我用这里的方式。
db.collection.find({ "Stories._id": "55c0bbd97abf0b941aafa169" }, { "Stories.$": 1 }).pretty()