我在聚合中使用match来返回任何具有匹配元素的文档,这些元素具有嵌入式数组和另一个数组。一个例子:
文档
{
name: "Frank",
favoriteColors: ["red", "pink", "orange"]
}
{
name: "Bob",
favoriteColors: ["blue", "red", "green"]
}
数组
let colors = ["blue", "maroon"];
因此,基本上,我想找到每个人(文档)最喜欢的颜色是蓝色或栗色的
答案 0 :(得分:2)
使用$in
运算符过滤一系列值。
插入脚本-
db.collection.insertMany([
{
"name": "Frank",
"favoriteColors": ["red", "pink", "orange"]
},
{
"name": "Bob",
"favoriteColors": ["blue", "red", "green"]
}]);
查询-
var query = {
favoriteColors: {
$in: ["blue", "maroon"]
}
};
db.collection.find(query);
输出-
/* 1 */
{
"_id" : ObjectId("5f12a14db00513b7c6ab6203"),
"name" : "Bob",
"favoriteColors" : [
"blue",
"red",
"green"
]
}
答案 1 :(得分:1)
类似这样的东西:
db.myCollection.find({ favoriteColors: { $in: ["blue", "maroon"] } })
您可以在此处找到更多文档 https://docs.mongodb.com/manual/reference/operator/query/in/#use-the-in-operator-to-match-values-in-an-array