我的应用程序有“帖子”,其中包含故事
现在我想从故事数组中的多个故事中选择一篇文章和其中的一个故事
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
匹配的故事
检查 this question 后我还尝试使用 $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:我正在使用monk,因此聚合不起作用
最佳答案
我无法复制您的示例文档,因此我使用了类似的文档:
{
"_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" : [ ]
}]
}
要得到你想要的,你需要使用dollar projection operator在某种程度上我在这里使用了它。
db.collection.find({
"Stories._id": "55c0bbd97abf0b941aafa169"
}, {
"Stories.$": 1
}).pretty()
关于node.js - 使用唯一 id 选择数组元素在 mongodb 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31911662/