如何查询mongodb以获取使用$ in存储在`var ids`数组中的id的文档?

时间:2015-12-26 20:16:47

标签: javascript json mongodb mongodb-query mongojs

我想从用户输入中传递给我的代码的某个数组中查询所有包含id的文档:

var attackersIds = fights[i].attackersIds;
attackers = cardsCollection.find({"_id" : { "$oid" : { $in: attackersIds } } });

问题是我收到错误:

MongoDB: Can't canonicalize query: BadValue unknown operator: $oid

我发现可以使用ObjectId(...)来解决,但是当我这样做时:

var attackersIds = fights[i].attackersIds;
for(var a=0; a<attackersIds.length; a++){
    attackersIds[a] = ObjectId(attackersIds[a]);
}
attackers = cardsCollection.find({"_id" : { "$oid" : { $in: attackersIds} } });

我收到另一个错误:

ReferenceError: \"ObjectId\" is not defined.

我想这是因为旧版本的node.js但我无法更改它,因为我的服务器提供商不允许我进行升级。

那么,如何向mongodb查询存储在var attackersIds数组中的id的文档?

样本文件:

{ "_id": { "$oid": "567ee17ae4b0128ba4ce9049" }, "classId": 9, "name": "Recruit", "description": "", "type": "creature", "cost": { "yellow": 1 }, "attack": 1, "defense": 0, "hp": 1, "area": "field1", "playerId": "56590c7ce4b03fe0cf20842d" }
{ "_id": { "$oid": "567ee17ae4b0128ba4ce904a" }, "classId": 1, "name": "Farm", "description": "", "type": "building", "cost": {}, "attack": 0, "defense": 0, "hp": 5, "generatesMana": { "yellow": 1 }, "area": "hand", "playerId": "56590c7ce4b03fe0cf20842d" }
{ "_id": { "$oid": "567ee17ae4b0128ba4ce904b" }, "classId": 1, "name": "Farm", "description": "", "type": "building", "cost": {}, "attack": 0, "defense": 0, "hp": 5, "generatesMana": { "yellow": 1 }, "area": "hand", "playerId": "56590c7ce4b03fe0cf20842d" }
{ "_id": { "$oid": "567ee17ae4b0128ba4ce904c" }, "classId": 9, "name": "Recruit", "description": "", "type": "creature", "cost": { "yellow": 1 }, "attack": 1, "defense": 0, "hp": 1, "area": "deck", "playerId": "56590c7ce4b03fe0cf20842d" }

3 个答案:

答案 0 :(得分:2)

尝试交换$ in和$ oid的订单

"_id": {
        "$in": [
            {
                "$oid": "54651022bffebc03098b4567"
            },
            {
                "$oid": "54651022bffebc03098b4568"
            }
        ]
   }

在你的情况下,你需要小辅助函数,从id的数组到$ oid字段的对象数组

attackers = cardsCollection.find({"_id" : { "$in" : attackersIds.map(function(element){
    return {
        "$oid": element
    });

答案 1 :(得分:0)

尝试将您的attackersIds数组转换为ObjectId类型的数组。你如何做到这取决于你用来查询mongodb集合的包。

与mongojs:

var mongojs = require('mongojs');
for(var a=0; a<attackersIds.length; a++){
    attackersIds[a] = mongojs.ObjectId(attackersIds[a]);
}

与mongodb:

ObjectID = require('mongodb').ObjectID;
for(var a=0; a<attackersIds.length; a++){
    attackersIds[a] = new ObjectId(attackersIds[a]);
}

然后尝试在_id上进行查询:

attackers = cardsCollection.find({"_id" : { $in: attackersIds } });

答案 2 :(得分:0)

您可以尝试将此类型投射到这样的目标:

mongoose.Types.ObjectId(string)

mongoose是你的猫鼬手柄:

var mongoose = require('mongoose')

或者您可能不需要:

CardsCollection.find({_id:{$in:attackersids}})