英文:
Mongodb: find documents where at least one item in an array exists in an array field
问题
Here is the translated code snippet using $match and $expr:
db.collection.aggregate([
{
$match: {
$expr: {
$in: [
"$favorites",
[
"apple",
"orange"
]
]
}
}
}
])
Please note that this code snippet should find documents in the collection where the "favorites" field contains either "apple" or "orange." If it's not returning any results, you may want to double-check your data and ensure that it matches the expected structure.
英文:
This is my data:
[
{
"_id": 1,
"name": "Alice",
"favorites": [
"apple",
"banana",
"cherry"
]
},
{
"_id": 2,
"name": "Bob",
"favorites": [
"banana",
"orange"
]
},
{
"_id": 3,
"name": "Charlie",
"favorites": [
"apple",
"cherry"
]
}
]
and I need to find the documents that have for example apple or orange in favorites field.
I know this works:
db.collection.aggregate([
{
$match: {
favorites: {
$in: [
"apple",
"orange"
]
}
}
}
])
also I know how to do it with find().
I need to do it with $match and $expr like:
db.collection.aggregate([
{
$match: {
$expr: {
$in: [
"$favorites",
[
"banana",
"orange"
]
]
}
}
}
])//Returns no data
but returns no result.
答案1
得分: 0
$ne
- 检查1.1的结果不是空数组。
1.1. $setIntersection
- 对favorite
和输入数组进行交集操作,返回一个包含交集的数组。
db.collection.aggregate([
{
$match: {
$expr: {
$ne: [
{
$setIntersection: [
"$favorites",
[
"banana",
"orange"
]
]
},
[]
]
}
}
}
])
英文:
In case you are still keen on working the query with $expr
operator,
$ne
- Check the result from 1.1 not an empty array.
1.1. $setIntersection
- Intersect the favorite
and input array to return an array with intersection.
db.collection.aggregate([
{
$match: {
$expr: {
$ne: [
{
$setIntersection: [
"$favorites",
[
"banana",
"orange"
]
]
},
[]
]
}
}
}
])
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论