尝试在PHP中聚合集合时出错。收集" lbls2"包含类似的文档:
{
"_id" : ObjectID(1234),
"values" : ["String 1", "String 2", "String 3"]
}
{
"_id" : ObjectID(5678),
"values" : ["String 1", "String 4", "String 7"]
}
{
"_id" : ObjectID(9101),
"values" : ["String 3", "String 5", "String 10"]
}
当我在Mongo shell中运行db.lbls2.aggregate({'$project' : {'values' : 1, '_id' : 0}})
时,它会返回:
{
"values" : [
"String 1",
"String 2",
"String 3"
]
}
{
"values" : [
"String 1",
"String 4",
"String 7"
]
}
{
"values" : [
"String 3",
"String 5",
"String 10"
]
}
当我在PHP中运行$r = $c_l->aggregate(['$project' => ['values' => 1, '_id' => 0]]);
时,它返回:
致命错误:未捕获的异常' MongoDB \ Exception \ InvalidArgumentException'使用消息' $ pipeline不是列表(意外索引:" $ project")'在C:\ xampp \ htdocs \ gc4 \ vendor \ mongodb \ mongodb \ src \ Operation \ Aggregate.php:93堆栈跟踪:#0 C:\ xampp \ htdocs \ gc4 \ vendor \ mongodb \ mongodb \ src \ Collection.php (186):MongoDB \ Operation \ Aggregate-> __ construct(' gc_dev',' lbls2',Array,Array)#1 C:\ xampp \ htdocs \ gc4 \ admin_dashboard.php (9):MongoDB \ Collection->在第93行的C:\ xampp \ htdocs \ gc4 \ vendor \ mongodb \ mongodb \ src \ Operation \ Aggregate.php中抛出的聚合(数组)#2 {main}
有趣的是,db.lbls2.aggregate({'$project' : {'values' : '$values.0', '_id' : 0}})
(投影值索引0)会返回' {"标签" :[]}',所以我可能搞砸了插入或做了一些奇怪的事情。我做错了什么?
这是我的PHP脚本: 要求(' ./ vendor / autoload.php');
$client = new MongoDB\Client("mongodb://localhost:27017");
$db = $client->gc_dev;
$c_l = $db->lbls2;
$r = $c_l->aggregate(['$project' => ['values' => 1, '_id' => 0]]);
这是我用来插入值的python脚本的一部分:
a = urllib2.urlopen('http://urlredacted.com')
a = bs(a)
length = len(a.findAll('a',id=re.compile('rptResults_*')))
for row in a.findAll('a',id=re.compile('rptResults_*')):
cells = row.get_text()
labels.append(cells)
lastIndex =len(labels)
for i in range (0,lastIndex):
labels[i] = unicodedata.normalize('NFKD',labels[i]).encode('ascii','ignore')
#connect to db and insert data
client = MongoClient("mongodb://localhost:27017")
db = client.gc_dev
c_lbls = db.lbls2
lbls_insert = {
"values" : labels
}
c_lbls.insert_one(lbls_insert)
答案 0 :(得分:2)
您使用的聚合参数不正确,来自mongodb库的代码:
- @param array $ pipeline管道操作列表
所以它期待一个管道操作列表,你传递一个关联数组并显示异常。产生异常的代码在这里:https://github.com/mongodb/mongo-php-library/blob/master/src/Operation/Aggregate.php#L93
解决方案是将一个数字数组作为管道命令列表传递。
$r = $c_l->aggregate([['$project' => ['values' => 1, '_id' => 0]]]);