[Database] MongoDB (4) Dot Notation 内嵌对象查询

Dot Notation   (Reaching into Objects) 内嵌对象查询

 

查看数据

In [4]: list(t.find())
Out[
4]:
[{u
'_id': ObjectId('4c6bf0fb421aa90705000000'),
u
'address': {u'city': u'shandong', u'postcode': 350, u'state': u'china'},
u
'age': 28,
u
'email': u'abeen_8298@msn.com',
u
'name': u'abeen'},
{u
'_id': ObjectId('4c6bf125421aa90705000001'),
u
'address': {u'city': u'beijing', u'postcode': 64, u'state': u'china'},
u
'age': 22,
u
'email': u'tangtang_0902@gmail.com',
u
'name': u'shanshan'}]

查找"address的city"为"shandong"

In [5]: list(t.find({"address.city":"shandong"}))
Out[
5]:
[{u
'_id': ObjectId('4c6bf0fb421aa90705000000'),
u
'address': {u'city': u'shandong', u'postcode': 350, u'state': u'china'},
u
'age': 28,
u
'email': u'abeen_8298@msn.com',
u
'name': u'abeen'}]

利用嵌入对象信息条件查找(嵌入对象的key和value必须全使用)

In [8]: list(t.find({"address":{"city": "shandong", "postcode": 350, "state": "china"}}))
Out[
8]:
[{u
'_id': ObjectId('4c6bf0fb421aa90705000000'),
u
'address': {u'city': u'shandong', u'postcode': 350, u'state': u'china'},
u
'age': 28,
u
'email': u'abeen_8298@msn.com',
u
'name': u'abeen'}]


Array Element by Position
数组元素按位置查找

In [24]: list(t.find({"name":"meinv"}))
Out[
24]:
[{u
'_id': ObjectId('4c6bf67c421aa9075c000000'),
u
'age': 46,
u
'likes': [u'apple', u'grape', u'watermelon'],
u
'name': u'meinv'},
{u
'_id': ObjectId('4c6bf7a4421aa9075c000001'),
u
'age': 46,
u
'comments': [{u'by': u'abeen', u'title': u'this is the title'},
{u
'by': u'shanshan', u'title': u'shuo wo ni shi shi'}],
u
'name': u'meinv'}]

查找爱好的第一项是"grape"的

In [25]: list(t.find({"likes.1": "grape"}))
Out[
25]:
[{u
'_id': ObjectId('4c6bf67c421aa9075c000000'),
u
'age': 46,
u
'likes': [u'apple', u'grape', u'watermelon'],
u
'name': u'meinv'}]

查找第一条评论是"abeen"发的信息

In [27]: list(t.find({"comments.0.by": "abeen"}))
Out[
27]:
[{u
'_id': ObjectId('4c6bf7a4421aa9075c000001'),
u
'age': 46,
u
'comments': [{u'by': u'abeen', u'title': u'this is the title'},
{u
'by': u'shanshan', u'title': u'shuo wo ni shi shi'}],
u
'name': u'meinv'}]



Matching with $elemMatch
 未完
 

原文地址:https://www.cnblogs.com/abeen/p/1802909.html