我的应用程序有“帖子”,其中有故事
现在我想从故事数组中的多个故事中选择一个帖子和其中一个故事
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
}
我希望它只返回帖子以及具有通过请求发送的故事 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) {
post文件的结构如下
{
"_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:我正在使用和尚,因此聚合不起作用