Return 具有相同子数组元素的文档
Return Documents with Same Subarray elements
我有以下合集:
{ "_id" : 1, "tags" : [ "school", "home" ] }
{ "_id" : 2, "tags" : [ "school", "storage", "home" ] }
{ "_id" : 3, "tags" : [ "school", "storage", "home", "bones" ] }
{ "_id" : 4, "tags" : [ "school", "storage", "home", "bones", "milk" ] }
{ "_id" : 5, "tags" : [ "homes", "maps", "bones" ] }
{ "_id" : 6, "tags" : [ "xxx", "yyy", "zzz" ] }
我想 return 所有“标签”与具有完全相同数组元素的文档相匹配的文档。
因此,如果我要查询标签 == ["school", "home"] 或标签 == ["home", "school"],文档 w/ _id=1 将是 returned
我正在做以下事情:
db.test.find({tags: {$in: ['school', 'home']}}) or
db.test.find({tags: {$in: ['home', 'school']}})
以下是 return编辑的:
{ "_id" : 1, "tags" : [ "school", "home" ] }
{ "_id" : 2, "tags" : [ "school", "storage", "home" ] }
{ "_id" : 3, "tags" : [ "school", "storage", "home", "bones" ] }
{ "_id" : 4, "tags" : [ "school", "storage", "home", "bones", "milk" ] }
我怎样才能实现只有 _id=1 的项目被 returned?
也许是这样的:
选项 1:
db.collection.find({
$and: [
{
tags: "school"
},
{
tags: "home"
},
{
tags: {
$size: 2
}
}
]
})
解释:
如果学校和家庭在标签数组中并且数组大小为 2,则匹配。
选项 2:
db.collection.find({
$or: [
{
tags: [
"school",
"home"
]
},
{
tags: [
"home",
"school"
]
}
]
})
解释:
匹配两个可能的数组选项
我有以下合集:
{ "_id" : 1, "tags" : [ "school", "home" ] }
{ "_id" : 2, "tags" : [ "school", "storage", "home" ] }
{ "_id" : 3, "tags" : [ "school", "storage", "home", "bones" ] }
{ "_id" : 4, "tags" : [ "school", "storage", "home", "bones", "milk" ] }
{ "_id" : 5, "tags" : [ "homes", "maps", "bones" ] }
{ "_id" : 6, "tags" : [ "xxx", "yyy", "zzz" ] }
我想 return 所有“标签”与具有完全相同数组元素的文档相匹配的文档。
因此,如果我要查询标签 == ["school", "home"] 或标签 == ["home", "school"],文档 w/ _id=1 将是 returned
我正在做以下事情:
db.test.find({tags: {$in: ['school', 'home']}}) or
db.test.find({tags: {$in: ['home', 'school']}})
以下是 return编辑的:
{ "_id" : 1, "tags" : [ "school", "home" ] }
{ "_id" : 2, "tags" : [ "school", "storage", "home" ] }
{ "_id" : 3, "tags" : [ "school", "storage", "home", "bones" ] }
{ "_id" : 4, "tags" : [ "school", "storage", "home", "bones", "milk" ] }
我怎样才能实现只有 _id=1 的项目被 returned?
也许是这样的:
选项 1:
db.collection.find({
$and: [
{
tags: "school"
},
{
tags: "home"
},
{
tags: {
$size: 2
}
}
]
})
解释:
如果学校和家庭在标签数组中并且数组大小为 2,则匹配。
选项 2:
db.collection.find({
$or: [
{
tags: [
"school",
"home"
]
},
{
tags: [
"home",
"school"
]
}
]
})
解释:
匹配两个可能的数组选项