[MONGO]我有一些像这样的地方:
[
{ item: "journal",tags: ["blank", "red","blue","yellow"]},
{ item: "notebook",tags: ["red", "pink","green"]},
{ item: "paper", tags: ["red", "blank", "plain","black"]},
{ item: "planner",tags: ["blank", "blue","gray"]},
{ item: "postcard",tags: ["blue"] }
]
我想搜索带有1个数组搜索的标签:[“red”,“blank”,“black”],如何获取项目,标签在aray搜索中包含至少1个元素。和排序。
期待结果:
[
{ item: "paper",tags: ["red", "blank", "plain","black"]},
{ item: "journal",tags: ["blank", "red","blue","yellow"]},
{ item: "notebook",tags: ["red", "pink","green"]},
{ item: "planner", tags: ["blank", "blue","gray"]},
]
答案 0 :(得分:0)
如果要查找集合myitems
中的所有文档,可以使用$or
operator,projection和sort function。
以下是查询如何找到任何标记为" red"," blank"或者"黑色":
db.myitems.aggregate([
{$project :
{tags: 1, item: 1, tag_count: {$size: "$tags" } }
},
{$match:
{$or: [{tags: "red"}, {tags: "blank"}, {tags: "black"}]}
},
{$sort: {"tag_count": -1} }
]);
这将返回如下内容:
{ "item" : "journal", "tags" : [ "blank", "red", "blue", "yellow" ], "tag_count" : 4 }
{ "item" : "paper", "tags" : [ "red", "blank", "plain", "black" ], "tag_count" : 4 }
{ "item" : "notebook", "tags" : [ "red", "pink", "green" ], "tag_count" : 3 }
{ "item" : "planner", "tags" : [ "blank", "blue", "gray" ], "tag_count" : 3 }
解释:
这使用MongoDB中的Aggregation pipeline,创建给定数据库的projection以获取"标记"大小,使用match projection和$or
operator对标记进行过滤,最后对"标记"进行排序。大小
希望这有帮助。