可以說我有一個貓鼬模式,例如:
mongoose.Schema({
website_id:mongoose.SchemaTypes.ObjectId,
data:Object
})
其中資料欄位包含 JSON 物件。就像是:
{
"actions":[
{
"action":"pageChange",
"url":"http://localhost:3000/login",
"dom":"",
"timestamp":1653341614846
},
{
"action":"pageChange",
"url":"http://localhost:3000/signup",
"dom":"",
"timestamp":1653341626442
},
{
"action":"pageChange",
"url":"http://localhost:3000/view",
"dom":"",
"timestamp":1653341626442
},
{
"action":"pageChange",
"url":"http://localhost:3000/login",
"dom":"",
"timestamp":1653341626442
}
]
}
有什么方法可以獲取所有檔案,其中資料欄位物件包含http://localhost:3000/login作為 url,而無需先獲取所有檔案并回圈它們。
物件將是動態生成的,并且專案將自我重復
uj5u.com熱心網友回復:
當然,有幾種方法,在這種情況下,最好的方法之一是使用“聚合”
db.collection.aggregate([
{$unwind: "$actions"},
{ $match: {"actions.url": "http://localhost:3000/login"}},
{$group: {
_id: "$_id",
actions: {$push: "$actions"}
}
}
])
回傳回應:
{
"actions": [
{
"action": "pageChange",
"dom": "",
"timestamp": 1.653341614846e 12,
"url": "http://localhost:3000/login"
},
{
"action": "pageChange",
"dom": "",
"timestamp": 1.653341626442e 12,
"url": "http://localhost:3000/login"
}
]
}
如果我找到其他或更好的方法,我一定會分享.. 我希望這個解決方案可以幫助你。
uj5u.com熱心網友回復:
你當然可以這樣做。您可以在查詢中以字串的形式指定物件嵌套。
await MyModel.find({ 'data.objectKey.items.item': 'text I want to find' }).exec();
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/483615.html
