Get the App
SLTechnology News&Howtos  ›  Database  › 

Data query of MongoDB (nested set)

Shulou Source: shulou.com Published: 2022-06-01 05:35:06 09月27日 Update

Each collection data in the MongoDB database can continue to save other collection data, for example, some people save family information.

Example: add data

Db.emp.insert ({"name": "Lin A", "sex": "male", "age": 22, "sal": 8000, "loc": "Beijing", "course": ["Chinese", "mathematics", "English", "music", "politics"], "parents": [{"name": "Lin A father", "age": 50, "job": "farmer"}, {"name": "Lin A mother", "age": 49 "job": "worker"}]})

Db.emp.insert ({"name": "Lin B", "sex": "male", "age": 30, "sal": 8000, "loc": "Beijing", "course": ["Chinese", "mathematics"], "parents": [{"name": "Lin B father", "age": 55, "job": "worker"}, {"name": "Lin B mother", "age": 52, "job": "farmer"}]})

Db.emp.insert ({"name": "Lin C", "sex": "male", "age": 35, "sal": 8000, "loc": "Beijing", "course": ["Chinese", "Mathematics", "English"], "parents": [{"name": "Lin C father", "age": 60, "job": "worker"}, {"name": "Lin C mother", "age": 59, "job": "staff"}]})

Db.emp.insert ({"name": "Lin D", "sex": "male", "age": 28, "sal": 8000, "loc": "Beijing", "course": ["Chinese", "Mathematics", "Politics"], "parents": [{"name": "Lin D Father", "age": 58, "job": "Director"}, {"name": "Lin D Mother", "age": 54, "job": "Director"]})

Db.emp.insert ({"name": "Lin E", "sex": "male", "age": 40, "sal": 8000, "loc": "Beijing", "course": ["language", "politics"], "parents": [{"name": "Lin E father", "age": 70, "job": "worker"}, {"name": "Lin E mother", "age": 68, "job": "Secretary"}]})

The content at this time is a nested collection, and the judgment of the data of this collection can only be done through "$elemMatch".

Example: find out the information of the director among the parents.

> db.emp.find ({"$and": [{"age": {"$gte": 30}}, {"parents": {"$elemMatch": {"job": "Director"}}]}) .pretty ()

{

"_ id": ObjectId ("599148bf0184ff511bf02b95")

"name": "Lin E"

"sex": "male"

"age": 40

"sal": 8000

"loc": "Beijing"

"course": [

"Chinese"

"politics"

]

"parents": [

{

"name": "Father Lin E"

"age": 70

"job": "worker

}

{

"name": "Mother Lin E"

"age": 68

"job": "Director"

}

]

}

Since the conditions of this kind of query are troublesome, try not to be so complicated if possible.

Tags: Mother father Chinese Beijing data director workers politics mathematics inquiry information farmers examples English complexity middle personnel content director family Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Information Xiaomi Linux MySQL OPPO Reno