Mongo Query Language 类似 Sql 语句

发布时间:2013-01-29 06:11:53

 

Mongo Query Language 类似 Sql 语句

$query - 查询类似于sql中的 where
$orderby - 排序{x:1},1为升序 -1为降序

$query - 查询类似于sql中的 where
$orderby - 排序{x:1},1为升序 -1为降序

//select * from table where name="abeen" order by age asc
In [28]: list(table.find({"$query" : {"name": "abeen"}, "$orderby": { "age": 1 }}))

//select * from table where name="abeen" order by age desc
In [29]: list(table.find({"$query" : {"name": "abeen"}, "$orderby": { "age": -1 }}))

//select name, address from table where name like '%a%'
按找指定字段按条件,并可指定排序 1:返回字段,0不返回字段


In [21]: list(t.find({"name":{"$regex": r".*a.*"}},{"name":1,  "address":1}))
Out[23]:
[{u'_id': ObjectId('4c5f9cbc421aa90fb9000000'), u'name': u'abeen'},
 {u'_id': ObjectId('4c5f9ccb421aa90fb9000001'), u'name': u'shanshan'},
 {u'_id': ObjectId('4c5f9d2d421aa90fb9000002'), u'name': u'shanshan2'},
 {u'_id': ObjectId('4c5f9d34421aa90fb9000003'), u'name': u'shanshan3'},
 {u'_id': ObjectId('4c5fa2ab421aa90fb9000004'), u'address': u'da zhong si', u'name': u'shanshan3'},
 {u'_id': ObjectId('4c5facc6421aa90fb9000005'), u'name': [u'abeen', u'a', u'b', u'e', u'e', u'n']},
 {u'_id': ObjectId('4c5fcd7e421aa90fb9000007'), u'name': u'abeen_object'},
 {u'_id': ObjectId('4c64b432421aa90697000000'), u'address': u'shandong', u'name': u'abeen'},
 {u'_id': ObjectId('4c64b438421aa90697000001'), u'address': u'shandong', u'name': u'abeen'},
 {u'_id': ObjectId('4c64b43d421aa90697000002'), u'address': u'shandong', u'name': u'abeen'},
 {u'_id': ObjectId('4c64b441421aa90697000003'), u'address': u'shandong', u'name': u'abeen'}]

0为不返回字段


In [24]: list(t.find({"name":{"$regex": r".*a.*"}},{"address":0}))
Out[24]:
[{u'_id': ObjectId('4c5f9cbc421aa90fb9000000'), u'age': 27, u'name': u'abeen'},
 {u'_id': ObjectId('4c5f9ccb421aa90fb9000001'), u'age': 22, u'name': u'shanshan'},
 {u'_id': ObjectId('4c5f9d2d421aa90fb9000002'), u'age': 22, u'name': u'shanshan2'},
 {u'_id': ObjectId('4c5f9d34421aa90fb9000003'), u'age': 23, u'name': u'shanshan3'},
 {u'_id': ObjectId('4c5fa2ab421aa90fb9000004'), u'age': 23, u'name': u'shanshan3'},
 {u'_id': ObjectId('4c5facc6421aa90fb9000005'), u'name': [u'abeen', u'a', u'b', u'e', u'e', u'n']},
 {u'_id': ObjectId('4c5fcd7e421aa90fb9000007'), u'name': u'abeen_object'},
 {u'_id': ObjectId('4c64b432421aa90697000000'), u'age': 22, u'name': u'abeen'},
 {u'_id': ObjectId('4c64b438421aa90697000001'), u'age': 23, u'name': u'abeen'},
 {u'_id': ObjectId('4c64b43d421aa90697000002'), u'age': 24, u'name': u'abeen'},
 {u'_id': ObjectId('4c64b441421aa90697000003'), u'age': 18, u'name': u'abeen'}]

 

go