Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mongodb 在查找中比较字符串和objectId_Mongodb_Aggregation Framework - Fatal编程技术网

Mongodb 在查找中比较字符串和objectId

Mongodb 在查找中比较字符串和objectId,mongodb,aggregation-framework,Mongodb,Aggregation Framework,我发现没有办法比较这两者。如果有其他选择,请告诉我 正如您所看到的,我有两个集合event和eventuser,我需要eventuser的用户列表 事件集合中事件名称的名称 但我有字符串格式的userId,那么如何比较userId列呢 在eventuser集合中具有_id列的事件中。 事件集合 { "_id" : ObjectId("5b5867500be60f139e67c908"), "userId" : "5b58674e0be60f139e67cfea", "name" : "Ad

我发现没有办法比较这两者。如果有其他选择,请告诉我

正如您所看到的,我有两个集合event和eventuser,我需要eventuser的用户列表 事件集合中事件名称的名称

但我有字符串格式的userId,那么如何比较userId列呢 在eventuser集合中具有_id列的事件中。 事件集合

{ 
"_id" : ObjectId("5b5867500be60f139e67c908"), 
"userId" : "5b58674e0be60f139e67cfea", 
"name" : "Add to Cart", 

},
{ 
"_id" : ObjectId("5b5867500be60f139e67c090"), 
"userId" : "5b58674e0be60f139e67cfea", 
"name" : "Searched", 

},
{ 
"_id" : ObjectId("5b5867500be60f139e67c098"), 
"userId" : "5b58674e0be60f139e67cacd", 
"name" : "Add to Cart", 

}


 EventUser Collection

{
"_id":ObjectId("5b58674e0be60f139e67cfea"),
 "name":"jogendra"
},
{
"_id":ObjectId("5b58674e0be60f139e67cfcv"),`
 "name":"jogendra singh"
}




 mmy query- it return users array as empty list
 db.getCollection("event").aggregate([
 {$match:{"name":"Add to Cart"}},
  {$lookup:{
 from:"eventuser",
 localField:"userId",
 foreignFiled:"_id",
 as:"users"
 }}
  ]);
在$lookup中,您不能与string->\u id或\u id->string匹配

可能的情况是_id->u id或string->string

所以你需要像这样改变你的数据

{ 
 "_id" : ObjectId("5b5867500be60f139e67c908"), 
 "userId" : ObjectId("5b58674e0be60f139e67cfea"), 
 "name" : "Add to Cart", 

},
{ 
 "_id" : ObjectId("5b5867500be60f139e67c090"), 
 "userId" : ObjectId("5b58674e0be60f139e67cfea"), 
 "name" : "Searched", 

},
{ 
 "_id" : ObjectId("5b5867500be60f139e67c098"), 
 "userId" : ObjectId("5b58674e0be60f139e67cacd"), 
 "name" : "Add to Cart", 

}
否则,您需要升级MongoDB版本4,并且可以使用$toObjectId


如果您有mongodb 4.0,那么您可以将userId从字符串转换为ObjectId,感谢Senthur我找到了另一个解决方案{$project:{convertedUserId:{$convert:{$input:$userId,to:ObjectId,onError:Cannot$convert to ObjectId}是,$convert可以将字符串转换为ObjectId,但它仅支持MongoDB最新版本。
db.collection.aggregate([
{ $match: { "name": "Add to Cart" } },
{
    $addFields: {
        convertedId: { $toObjectId: "$userId" }
    }
},
{
    "$lookup": {
        "from": "from_collection",
        "localField": "convertedId",
        "foreignField": "_id",
        "as": "data"
    }
}
]);