我有一個這樣的架構:
const AyoSchema = new Schema({
images: Array,
影像是一個陣列,其中物件以這種格式存盤:
{
id: a uuid here,
name: a string here,
url: a url here,
topic: a string here
}
我想要做的是,我想搜索影像陣列中所有物件的名稱屬性,而不涉及大量索引作業,
我該怎么辦?
uj5u.com熱心網友回復:
有幾種方法可以處理它。如果您只想回傳匹配的檔案,則要復雜一些。
我假設您只想回傳匹配的專案。為此,您需要使用聚合管道,特別是 $unwind 和 $match 運算子。
在這里查看現場演示
考慮以下:
資料庫
[
{
_id: ObjectId("111111111111111111111111"),
images: [
{
id: ObjectId("123123224454323123121314"),
name: "foo",
url: "cdn.domain.com/images/foo",
topic: "lorem ipsum"
},
{
id: ObjectId("222123224454323123121314"),
name: "bar",
url: "cdn.domain.com/images/bar",
topic: "lorem ipsum"
},
{
id: ObjectId("333323224454323123121314"),
name: "baz",
url: "cdn.domain.com/images/baz",
topic: "lorem ipsum"
}
]
},
{
_id: ObjectId("222222222222222222222222"),
images: [
{
id: ObjectId("888823224454323123121314"),
name: "text",
url: "cdn.domain.com/images/text",
topic: "lorem ipsum"
},
{
id: ObjectId("999993224454323123121314"),
name: "foo",
url: "cdn.domain.com/images/pic",
topic: "lorem ipsum"
}
]
}
]
詢問
db.collection.aggregate([
{
$unwind: "$images"
},
{
$match: {
"images.name": "foo" // <-- replace "foo" with your query
}
}
])
結果
[
{
"_id": ObjectId("111111111111111111111111"),
"images": {
"id": ObjectId("123123224454323123121314"),
"name": "foo",
"topic": "lorem ipsum",
"url": "cdn.domain.com/images/foo"
}
},
{
"_id": ObjectId("222222222222222222222222"),
"images": {
"id": ObjectId("999993224454323123121314"),
"name": "foo",
"topic": "lorem ipsum",
"url": "cdn.domain.com/images/pic"
}
}
]
更新
包括正則運算式。
現場演示
詢問
db.collection.aggregate([
{
$unwind: "$images"
},
{
$match: {
"images.name": {
"$regex": "fo*"
}
}
}
])
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/405576.html
標籤:
下一篇:Mongoose:深度搜索
