我有陣列:
{'_id': ObjectId('7262718c217dda3ad90ef151'), 'SomeText': "aaa", 'items': [{'status': 500, 'x': 1, 'y': None, 'price': 3}, { 'status': 500, 'x': 2, 'y': None, 'price': 4}]}
{'_id': ObjectId('7262718c217dda3ad90ef152'), 'SomeText': "bbb", 'items': [{'status': 300, 'x': 1, 'y': 2, 'price': 7}, { 'status': 500, 'x': 2, 'y': 2, 'price': 5}]}
{'_id': ObjectId('7262718c217dda3ad90ef153'), 'SomeText': "ccc", 'items': [{'status': 300, 'x': 1, 'y': 1, 'price': 8}]}
我只需要查找那些x不等于y并且只有欄位“SomeText”、“х”、“y”的值的檔案
詢問:
fx = mycol.find({"$expr": {"$ne": ["$items.x", "$items.y"]}},
{ "_id": 0, "SomeText": 1, "items.x": 1, "items.y": 1, }
).limit(3)
for x in fx:
print(x)
回傳具有形狀中所有陣列項的檔案,但我想僅獲取包含x不等于y的陣列的檔案
{'SomeText': "aaa" 'items': [{'x': 1, 'y': None,}, {'x': 2, 'y': None,}]}
{'SomeText': "bbb", 'items': [{'x': 1, 'y': 2}, {'x': 2, 'y': 2]}
詢問:
fx=mycol.aggregate([
{"$match": {"$expr": {"$ne": ["$items.x", "$items.y"]}}},
{"$project": {
"items": {"$filter": {
"input": '$items',
"as": 'item',
"cond": {"$ne": ["$$item.x", "$$item.y"]}
}},
"_id": 0, "SomeText": 1
}},
{"$limit" : 5}
])
for x in fx:
print(x)
回傳帶有“狀態”和“價格”的檔案
{'SomeText': "aaa", 'items': [{'status': 500, 'x': 1, 'y': None, 'price': 3}, { 'status': 500, 'x': 2, 'y': None, 'price': 4}]}
{'SomeText': "bbb", 'items': [{'status': 300, 'x': 1, 'y': 2, 'price': 7}]}
我可以過濾陣列中的元素以獲得結果嗎?
{'SomeText': "aaa", 'items': [{'x': 1, 'y': None,}, {'x': 2, 'y': None,}]}
{'SomeText': "bbb", 'items': [{'x': 1, 'y': 2}]}
uj5u.com熱心網友回復:
$map只需在當前查詢中添加一個步驟:
db.collection.aggregate([
{
$match: {$expr: {$ne: ["$items.x", "$items.y"]}}
},
{
$project: {
items: {
$filter: {
input: "$items",
as: "item",
cond: {$ne: ["$$item.x", "$$item.y"]}
}
},
_id: 0,
SomeText: 1
}
},
{
$set: {
items: {
$map: {
input: "$items",
as: "item",
in: {x: "$$item.x", y: "$$item.y"}
}
}
}
},
{
$limit: 5
}
])
看看它在操場上的例子是如何作業的
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/487235.html
