使用在mongodb中工作的唯一ID选择数组元素

时间:2015-08-10 04:31:28

标签: node.js mongodb monk

我的申请有"帖子"这将有故事

现在我想从故事数组中的多个故事中选择一个帖子,只选择其中一个故事

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的故事,但它返回故事数组中的所有故事

enter image description here

我在这里收到该帖子的所有故事,因为我只需要与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) {

邮寄文件的结构如下

{
    "_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:我正在使用和尚,因此聚合不起作用

1 个答案:

答案 0 :(得分:2)

我无法复制您的示例文档,因此我使用了类似文档:

db.collection.find({
   "Stories._id": "55c0bbd97abf0b941aafa169"
}, {
   "Stories.$": 1
}).pretty()

要获得您想要的内容,您需要以我在此处使用的方式使用dollar projection operator

foreach(var objTemp in objList) {
    bool isNotSimilar = true;
    foreach(string property in otherProperties) {
        //get sending object property data
        object tempFValue = (objTemp as IDictionary < string, Object > )[property];
        //get current  object property data
        object tempCValue = (dynamicObj as IDictionary < string, Object > )[property];
        if (!tempFValue.Equals(tempCValue)) {
            isNotSimilar = false;
            break;
        }
    }
    if (isNotSimilar) {
        isDuplicate = true;
        break;
    }
}