Ubuntu 10.04.3 LTS mongodb-1.2.2-1ubuntu1.1 django 1.3 mongoengine-0.5.2 pymongo-2.1.2
模型:
class User(Document):
email = StringField(required=True)
first_name = StringField(max_length=50)
last_name = StringField(max_length=50)
class Comment(EmbeddedDocument):
content = StringField()
name = StringField(max_length=120)
class Post(Document):
title = StringField(max_length=120, required=True)
author = ReferenceField(User)
tags = ListField(StringField(max_length=30))
comments = ListField(EmbeddedDocumentField(Comment))
class TextPost(Post):
content = StringField()
class ImagePost(Post):
image_path = StringField()
class LinkPost(Post):
link_url = StringField()
Run Code Online (Sandbox Code Playgroud)
试图保存标题中包含"é"的帖子:
john = User(email='jdoe@example.com', first_name='John', last_name='Doe')
john.save()
post1 = TextPost(title='Fun with MongoEnginée', author=john)
post1.content = 'Took a look at MongoEngine today, looks …Run Code Online (Sandbox Code Playgroud) 我开始使用pymongo(版本2.2.1)ReplicaSetConnection对象而不是pymongo.Connection对象.现在,当我从数据库执行读取时,例如:
if cur.count() == 0:
raise NoDocumentsFound(self.name, self.COLLECTION_NAME)
elif cur.count() > 1:
raise TooManyDocumentsFound(self.name, self.COLLECTION_NAME)
cur.rewind()
rec = cur[0]
Run Code Online (Sandbox Code Playgroud)
我有时会在最后一行收到" IndexError:Cursor实例没有这样的项 ".从我可以找到有关此错误的所有内容,只有当您没有任何与您的查询匹配的记录时才会发生此错误.但是,我已经清楚地检查过我的光标中有项目.ReplicaSetConnection是否存在奇怪的问题,这使得这些读取操作更加不稳定?
我需要根据字段"X"的唯一值删除重复的条目.它在mongodb shell中工作正常:
db.collection.ensureIndex({x' : 1},{unique: true, dropDups: true})
Run Code Online (Sandbox Code Playgroud)
我想用pymongo运行它,我使用的代码如下:
import pymongo
import mmh3
conn = pymongo.MongoClient()
db = conn['scrapy-mongodb']
db.collection.ensure_index({'x' : 1}, {'$unique' : True, '$dropDups' : True})
Run Code Online (Sandbox Code Playgroud)
此代码抛出:
TypeError:如果未指定方向,则key_or_list必须是list的实例
我哪里做错了?
我试图在 count() = 1 时做一些事情。我通过打印出来确认了 cursor.count() == 1,但是当我使用 cursor[0] 时,它引发了一个异常。
if not cursor.count():
return self.create_new_incident(tweet)
elif loc_cur.count() == 1:
return self.update_existing_incident(tweet, cursor[0])
....
File "/Library/Python/2.7/site-packages/pymongo/cursor.py", line 588, in __getitem__
raise IndexError("no such item for Cursor instance")
Run Code Online (Sandbox Code Playgroud)
IndexError: Cursor 实例没有这样的项目
我读到: 使用 pymongo 的 ReplicaSetConnection:有时会收到“IndexError:光标没有这样的项目” 我已经关闭了其他未使用的连接,但仍然无法正常工作。
提前致谢
我有一个包含 0.6 百万个文档的集合。大多数文件的结构如下,
{
"_id" : ObjectId("53d86ef920ba274d5e4c8683"),
"checksum" : "2856caa9490e5c92aedde91330964488",
"content" : "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\r\n<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"bn-bd\" lang=\"bn-bd\" dir=\"ltr\" " />\n <link rel=\"stylesheet\" href=\"/templates/beez_20/css/position.css\" type=\"text/css\" media=\"screen,projection\ef=\"/index.php/bn/contact-bangla/2013-0</body>\r\n</html>",
"date" : ISODate("2014-07-29T15:57:11.886Z"),
"filtered_content" : "",
"indexed" : true,
"category": 'raw',
"link_extracted" : 1,
"parsed" : true,
"title" : "Constituency 249_10th_En",
"url" : "http://www.somesite.com.bd/index.php/bn/bangla/2014-03-23-11-45-04?layout=edit&id=2143"
}
Run Code Online (Sandbox Code Playgroud)
所有文档都带有日期属性。现在,当我编写下面的查询时,我得到了无限期的延迟时间来显示结果。
from pymongo import Connection
import datetime
con = Connection()
db = con.spider
pages = db.pages
today = datetime.datetime.combine( datetime.date.today(), datetime.datetime.min.time() ) …Run Code Online (Sandbox Code Playgroud) 我有一个基于异步 Tornado 和 mongoDB 的 API。它工作正常,除了一个处理程序:
@gen.coroutine
def get(self, *args, **kwargs):
"""
Gets tracking lib
"""
data = self._get_request_data()
self._serialize_request_data(AuthValidator, data)
tags = yield self.motor.tags.find_one({"client_id": data["client_id"]})
raise Return(self.write(tags))
Run Code Online (Sandbox Code Playgroud)
当请求到来时,tornado 返回带有以下堆栈跟踪的 HTTP 500:
response: Traceback (most recent call last):
File "/Users/artemkorhov/Projects/cartreminder/env/lib/python2.7/site-packages/tornado/web.py", line 1334, in _execute
result = yield result
File "/Users/artemkorhov/Projects/cartreminder/env/lib/python2.7/site-packages/tornado/gen.py", line 617, in run
value = future.result()
File "/Users/artemkorhov/Projects/cartreminder/env/lib/python2.7/site-packages/tornado/concurrent.py", line 109, in result
raise_exc_info(self._exc_info)
File "/Users/artemkorhov/Projects/cartreminder/env/lib/python2.7/site-packages/tornado/gen.py", line 620, in run
yielded = self.gen.throw(*sys.exc_info())
File "/Users/artemkorhov/Projects/cartreminder/cartreminder_app/tracking_api/api_handlers/endpoints.py", line 35, in get
tags …Run Code Online (Sandbox Code Playgroud) 我正在创建一个字符串,然后我在一个查询mongodb集合的方法中使用它.最终日期将来自用户输入.这是相关的代码和字符串:
import pymongo
from pymongo import MongoClient
from datetime import datetime
import time
import datetime
start_yr = 2015
start_mnth = 2
start_day = 1
end_yr = 2015
end_mnth = 2
end_day = 28
# this is the line called in the error
created_at_string = { "created_at": {"$gte" : datetime(start_yr, start_mnth, start_day),"$lt" : datetime(end_yr, end_mnth, end_day)}}
Run Code Online (Sandbox Code Playgroud)
这个想法将created_at_string用作更复杂的查询方法中的参数.
我越来越:
Traceback (most recent call last):
File "main.py", line 218, in <module>
program.runProgram()
File "main.py", line 61, in runProgram
report.RcreateReport()
File "/filepath/report.py", …Run Code Online (Sandbox Code Playgroud) 我正在使用Django和MongoDB构建一个网站.有2个,我们可以用它来连接流行的API框架Django和MongoDB,一个是mongoengine,另一个是django-mongodb-engine.
因为mongoengine不再支持Django 最新的Document,并且django-mongodb-engine需要另一个django-nonrel使开发环境有点复杂的软件包.
我想知道,如果我可以使用Pymongo连接Django和MongoDB直接.
有没有人可以分享相同的经验?以及如何setting.py在Django中设置db in 以使db公开?
我正在使用pymongo"insert_one",我想阻止插入具有相同"name"属性的两个文档.
谢谢!
我的代码:
client = MongoClient('mongodb://localhost:8888/db')
db = client[<db>]
heights=db.heights
post_id= heights.insert_one({"name":"Tom","height":2}).inserted_id
try:
post_id2 = heights.insert_one({"name":"Tom","height":3}).inserted_id
except pymongo.errors.DuplicateKeyError, e:
print e.error_document
print post_id
print post_id2
Run Code Online (Sandbox Code Playgroud)
输出:
56aa7ad84f9dcee972e15fb7
56aa7ad84f9dcee972e15fb8
I have this simple JSON in mongodb:
{
"pwd_list": [
{
"pwd": "password1",
"pwd_date": str(int(time.time()))
},
{
"pwd": "password2",
"pwd_date": str(int(time.time()))
},
]
}
Run Code Online (Sandbox Code Playgroud)
What I am simply trying to do is to update one of the row of the pwd_list array using an index...
I tried to use the $position of mongodb but it seems to only work with $push... but I don't want to push !
(I'm using pymongo)
So I tried different things like this one : …
pymongo ×10
mongodb ×9
python ×6
django ×2
mongoengine ×2
python-2.7 ×2
arrays ×1
cursor ×1
nosql ×1
replication ×1
tornado ×1
utf-8 ×1