我有一个简单的集合。
> db.y.find({}, {'_id': 1})
{ "_id" : ObjectId("5908e63cd15fa104356eaf64") }
{ "_id" : ObjectId("5908e63cd15fa104356eaf65") }
{ "_id" : ObjectId("5908e63cd15fa104356eaf66") }
{ "_id" : ObjectId("5908e63cd15fa104356eaf67") }
{ "_id" : ObjectId("5908e63cd15fa104356eaf68") }
{ "_id" : ObjectId("5908e63cd15fa104356eaf69") }
{ "_id" : ObjectId("5908e63cd15fa104356eaf6a") }
{ "_id" : ObjectId("5908e63cd15fa104356eaf6b") }
我想经营一个简单聚合管道(大大简化了解释)
我运行这个蒙戈shell脚本:
print('find')
result = db.y.find({ '_id': ObjectId("5908e63cd15fa104356eaf64") }, {'_id':1})
while (result.hasNext()) { printjson(result.next()); }
print('aggregate match direct')
result = db.y.aggregate([ {'$match': {'_id': ObjectId("5908e63cd15fa104356eaf64") } }, {'$project': {'_id': 1}} ])
while (result.hasNext()) { printjson(result.next()); }
print('aggregate match with $eq')
result = db.y.aggregate([ {'$match': {'_id': {'$eq': ObjectId("5908e63cd15fa104356eaf64") } } }, {'$project': {'_id': 1}} ])
while (result.hasNext()) { printjson(result.next()); }
print('aggregate match with $ne')
result = db.y.aggregate([ {'$match': {'_id': {'$ne': ObjectId("5908e63cd15fa104356eaf64") } } }, {'$project': {'_id': 1}}, {'$limit': 5} ])
while (result.hasNext()) { printjson(result.next()); }
这个结果(这是绝对正确)
find
{ "_id" : ObjectId("5908e63cd15fa104356eaf64") }
aggregate match direct
{ "_id" : ObjectId("5908e63cd15fa104356eaf64") }
aggregate match with $eq
{ "_id" : ObjectId("5908e63cd15fa104356eaf64") }
aggregate match with $ne
{ "_id" : ObjectId("5908e63cd15fa104356eaf65") }
{ "_id" : ObjectId("5908e63cd15fa104356eaf66") }
{ "_id" : ObjectId("5908e63cd15fa104356eaf67") }
{ "_id" : ObjectId("5908e63cd15fa104356eaf68") }
我想将其转换为蟒蛇如下:
...
print('find')
result = y.find({ '_id': 'ObjectId("5908e63cd15fa104356eaf64")' }, {'_id':1})
for i, o in enumerate(result):
print(i, o)
print('aggregate match direct')
result = y.aggregate([ {'$match': {'_id': 'ObjectId("5908e63cd15fa104356eaf64")' } }, {'$project': {'_id': 1} } ])
for i, o in enumerate(result):
print(i, o)
print('aggregate match with $eq')
result = y.aggregate([ {'$match': {'_id': {'$eq': 'ObjectId("5908e63cd15fa104356eaf64")' } } }, {'$project': {'_id': 1} } ])
for i, o in enumerate(result):
print(i, o)
print('aggregate match with $ne')
result = y.aggregate([ {'$match': {'_id': {'$ne': 'ObjectId("5908e63cd15fa104356eaf64")' } } }, {'$project': {'_id': 1} }, {'$limit': 5} ])
for i, o in enumerate(result):
print(i, o)
这个结果:
find
aggregate match direct
aggregate match with $eq
aggregate match with $ne
0 {'_id': ObjectId('5908e63cd15fa104356eaf64')}
1 {'_id': ObjectId('5908e63cd15fa104356eaf65')}
2 {'_id': ObjectId('5908e63cd15fa104356eaf66')}
3 {'_id': ObjectId('5908e63cd15fa104356eaf67')}
4 {'_id': ObjectId('5908e63cd15fa104356eaf68')}
结论:
的$匹配操作从未采取的ObjectId语法考虑。
如何正确写入?
感谢您的任何提示
基督教
您正在使用PyMongo正确的吗? 'Y'是一个游标对象 – jwillis0720