我有mongodb文件
{
"_id" : ObjectId("4e8ae86d08101908e1000001"),
"name" : ["Some Name","Another"],
"zipcode" : ["2223"]
}
{
"_id" : ObjectId("4e8ae86d08101908e1000002"),
"name" : ["Another", "Name"],
"zipcode" : ["2224"]
}
{
"_id" : ObjectId("4e8ae86d08101908e1000003"),
"name" : ["Yet", "Another", "Name"],
"zipcode" : ["2225"]
}
我需要找到“name array”具有“Another”,“Name”值的元素。 我尝试使用$ in,但是如果有更多的值,比如
{
"_id" : ObjectId("4e8ae86d08101908e1000003"),
"name" : ["Yet", "Another", "Name"],
"zipcode" : ["2225"]
}
它没有返回=(
答案 0 :(得分:3)
只要您的数据正确且值不包含任何空格,$ in的使用应该没问题(如下所述)。但如果它们完全相同,那么您需要进行一些$regex匹配,同时使用$and形式:
db.collection.find({
$and: [
{name: {$regex: 'Another'} },
{name: {$regex: 'Name'}}
]
})
如果您只想获得一个既包含又 所需字段值的文档,又在相同顺序中提供参数作为阵列:
db.collection.find({ name: ["Another", "Name" ] })
$in的用法是将您提供的任何元素作为列表进行匹配。在这种情况下,您将匹配所有文档
db.collection.find({ name: {$in: [ "Another", "Name" ] } })
对于$all运算符,它的作用是匹配参数列表中包含的所有元素,因此如果正在搜索的数组中不存在参数,则不会包含该参数。所以只有最后两个匹配:
db.collection.find({ name: {$all: [ "Another", "Name" ] } })
{
"_id" : ObjectId("4e8ae86d08101908e1000002"),
"name" : ["Another", "Name"],
"zipcode" : ["2224"]
}
{
"_id" : ObjectId("4e8ae86d08101908e1000003"),
"name" : ["Yet", "Another", "Name"],
"zipcode" : ["2225"]
}
最后,如果你不知道你匹配的元素的顺序,虽然有点做作,aggregate为你提供了一个离开监狱的方法< / EM>:
db.collection.aggregate([
// Match using $all to reduce the list
{$match: {name: {$all: ["Name","Another"] }}},
// Keep the original document in the _id
{$project:{
_id: {
_id: "$_id",
name: "$name",
zipcode: "$zipcode"
},
name: 1
}},
// Unwind the "name" array
{$unwind: "$name"},
// Count up the entries per _id
{$group: { _id: "$_id", count: {$sum: 1}}},
// Only match *2* as there were two elements we were expecting
{$match: {count: 2} },
// Project back to the original form
{$project: {
_id:0,
_id: "$_id._id",
name: "$_id.name",
zipcode: "$_id.zipcode"
}}
])
这就是我能想到的所有形式。
答案 1 :(得分:2)