问题1:使用点符号进行筛选:"subject.book.Year Pub"
db.Subject.aggregate([
{
"$unwind": "$subject.book"
},
{
"$match": {
"subject.book.yearPub": 2022
}
},
{
"$project": {
"subject.book.ISBN": 1,
"subject.book.bookTitle": 1
}
}
])
Demo Q1 @ Mongo Playground个
Updated: To filter the document in the array个个
db.collection.aggregate([
{
"$match": {
"subject.book.yearPub": 2022
}
},
{
$set: {
"subject.book": {
$filter: {
input: "$subject.book",
cond: {
$eq: [
"$$this.yearPub",
2022
]
}
}
}
}
},
{
"$project": {
"subject.book.ISBN": 1,
"subject.book.bookTitle": 1
}
}
])
Demo Q1.1 @ Mongo Playground个
问题2:我怀疑你对结果的观察不正确.当索引从0开始时,subject.book.author.3
将返回subject.book.author
数组中的第四个元素.
对于您当前的查询,它将返回具有subject.book.author
个数组中的第三个和第四个元素的文档,这意味着只要该数组包含more than 2个元素,就会返回该文档.
相反,您需要使用$size
运算符来获取数组的大小.虽然有些文档没有book
属性,因此使用$ifNull
返回空数组,以防止在使用$size
时出错.
db.Subject.aggregate([
{
"$match": {
$expr: {
$in: [
{
$size: {
$ifNull: [
"$subject.book.author",
[]
]
}
},
[
2,
3
]
]
}
}
},
{
"$project": {
"subject.book.ISBN": 1,
"subject.book.bookTitle": 1,
"subject.book.publisher": 1,
"_id": 0
}
}
])
Demo Q2 @ Mongo Playground个
Updated: To filter the document in the array个个
db.collection.aggregate([
{
"$match": {
$expr: {
$in: [
{
$size: {
$ifNull: [
"$subject.book.author",
[]
]
}
},
[
2,
3
]
]
}
}
},
{
$set: {
"subject.book": {
$filter: {
input: "$subject.book",
cond: {
$in: [
{
$size: {
$ifNull: [
"$subject.book.author",
[]
]
}
},
[
2,
3
]
]
}
}
}
}
},
{
"$project": {
"subject.book.ISBN": 1,
"subject.book.bookTitle": 1,
"subject.book.publisher": 1,
"_id": 0
}
}
])
Demo Q2.1 @ Mongo Playground个
Note: You attach too many questions into one. Please remember to split it into different questions (posts) when you ask a new question in the future.个