[英]How to find all documents with all specified array values in it in mongoDB?
這是我的收藏
{
"_id" : ...,
"name" : "sport",
}
{
"_id" : ...,
"name" : "art",
}
{
"_id" : ...,
"name" : "cars",
}
這是一個數組我有["cars","sport"]
我只是想確保我有cars
和 sport
在我的收藏,如果沒有(或只是一個不存在的),我想收到什么 。 我在尋找像$ in but 和 mode這樣的查詢友好數組。
這是你在找什么..?
db.colllection.find( {$and: [ {"name": {$in: ["cars"]}}, {"name": {$in: ["sports"]}} ] })
以下查詢應該可以幫助您實現這一目標
//change test with your collection name
db.getCollection('test').aggregate(
{
$group: {
_id: "collectionOfNames",
"names": {$addToSet: "$name"}
}
},
{
$match: {"names": {$all: ["cars", "sport"]}}
}
)
我們使用$ group在所有文檔中創建屬性名稱的數組“名稱”。 然后使用$ match和$ all進行檢查,以確保數組“名稱”包含查詢數組中的所有元素。
這是你想要的?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.