英文:
I want to query into Mongodb using python
问题
我想使用Python(pymongo)从MongoDB中查找和更新特定字段。以下是数据库的确切结构:
id: 2
Name: "CHK-MG-3"
NumberOfWorkbenches: 170
AllocatedWorkbenches: 0
BenchDetails: Array (17)
~ 0: Object
seatRowLabel: "A"
IsRowSpace: false
~ seats: Array (13)
0: object
key: "A_1"
status: "available"
BenchName: ""
IsAllocated: True
IsRequested: false
seatNo: ""
seatLabel: ""
dir: ""
labelNo: "x12"
team: ""
AllocationData: Array (1)
0: Object
id: 111
Program: "STL"
Duration: "3 days"
Team: "Frankenstein"
首先,我想查找Name为"CHK-MG-3"的记录,然后在BenchDetails下,以及在seats数组内,检查labelNo是否为"x12",并将IsAllocated设置为false,将AllocationData设置为None。
英文:
I want to find and update specific fields from mongodb using python(pymongo)
Below is the exact structure of db
id: 2
Name: "CHK-MG-3"
NumberOfWorkbenches: 170
AllocatedWorkbenches: 0
Benchbetails: Array (17)
~ 0: Object
seatRowLabel: "A"
IsRowspace: false
~ seats: Array (13)
0: object
key: "A_1"
status: "available"
BenchName: ""
IsAllocated: True
IsRequested: false
seatNo: ""
seatLabel: ""
dir: ""
labelNo: "x12"
team: ""
AllocationData: Array (1)
0:Object
id:111
Program:"STL"
Duration:"3 days"
Team:"Frankestein"
First i want to find Name:"CHk-MG-3",then under the benchdetails, and inside seats(array) check for labelNo:x12 and update isallocatedto: false and AllocationData to None.
答案1
得分: 1
我认为你可以尝试使用arrayFilters两次来执行此查询,因为它涉及到嵌套数组:
通过这个查询,你告诉Mongo:
- 仅在
Name
为CHK-MG-3
或Benchbetails.seats.labelNo
内部具有值为x12
的属性的对象中执行更新。这样,你可以避免在arrayFilters
阶段对整个集合进行过滤。 - 然后更新
bench.seats.seat
下定义的值。 bench
是Benchbetails
数组中seats.labelNo
为x12
的对象,seat
是seats
数组中labelNo
为x12
的对象。
因此,你只更新所需的嵌套数组值,将IsAllocated
设置为False
,AllocationData
设置为None
。
collection.update_many(
{
"Name": "CHK-MG-3",
"Benchbetails.seats.labelNo": "x12"
},
{
"$set": {
"Benchbetails.$[bench].seats.$[seat].IsAllocated": False,
"Benchbetails.$[bench].seats.$[seat].AllocationData": None
}
},
array_filters=[
{"bench.seats.labelNo": "x12"},
{"seat.labelNo": "x12"}
]
)
示例在这里。
英文:
I think you can try this query using arrayFilters twice because the nested array:
With this query you are telling mongo:
- Do the update only into objects where
Name
isCHK-MG-3
or has a property insideBenchbetails.seats.labelNo
with valuex12
. Using this you can avoid to filter the entire collection intoarrayFilters
stage. - Then update values where
bench.seats.seat
is defined just below. bench
is the object in theBenchbetails
array whereseats.labelNo
isx12
andseat
is the object intoseats
array wherelabelNo
isx12
.
So you are updating only the desired value into nested array setting IsAllocated
as False
and AllocationData
as None
.
collection.update_many(
{
"Name": "CHK-MG-3",
"Benchbetails.seats.labelNo": "x12"
},
{
"$set": {
"Benchbetails.$[bench].seats.$[seat].IsAllocated": False,
"Benchbetails.$[bench].seats.$[seat].AllocationData": None
}
},
array_filters=[
{"bench.seats.labelNo": "x12"},
{"seat.labelNo": "x12"}
]
)
Example here
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论