db.collection.distinct()的返回值

问题描述:

我有一个我已经插入到MongoDB中的集合。我想使用db.coll.distinct(key)检索一个特定的值,并将其用作更新函数的值。示例Python代码如下:db.collection.distinct()的返回值

post = {key:value} 
db.filesystem3.insert(post) 
value1 = "testing" 
ret = db.filesystem3.distinct(key) 
db.filesystem3.update({key:ret},{"$set":{key:value1}}) 
result = db.filesystem3.find() 
for i in result: 
    print i 

该文档没有得到更新。我在这里错过了什么,或者我们不能使用独特的领域进行更新?

+0

['collection.distinct'](http://api.mongodb.org/python/current /api/pymongo/collection.html#pymongo.collection.Collection.distinct)返回不同值的列表。你为什么认为你需要'.distinct'?也许有更好的方法来做你想做的事情,所以请用你的问题[编辑链接](http://*.com/posts/33138369/edit)来显示预期结果的示例文档。 – styvane

对distinct的调用返回一个列表,因此您需要迭代每个返回的值。

ret = db.filesystem3.distinct(key) 
for ret_value in ret: 
    db.filesystem3.update({key:ret_value}, {"$set": {key: value1}}) 

RET = db.filesystem3.distinct(键)线将返回一个数组,所以不能直接传递数组更新文档

行为DISTINCT运算符的

不同的运算符在单个集合中查找指定字段的不同值,并且返回数组中的结果。

数组字段如果指定字段的值是一个数组, db.collection.distinct()会将该数组的每个元素视为一个单独的值作为 单独的值。 http://docs.mongodb.org/manual/reference/method/db.collection.distinct/

您可以更新这样的代码

for(var i=0;i<ret.length;i++){ 
var val = ret[i]; 
db.filesystem3.update({key:val},{"$set":{key:value1}}); 
} 

希望这将有助于