[英]Exact match document in MongoDB
我目前在 Java 应用程序上使用 MongoDB 的驱动程序。 假设我将以下两个文档存储在一个集合中:
文件 A:
{
"_id": "something",
"key1": "Value1",
"Key2": "Value2",
"Key3": "Value3"
}
文件 B:
{
"_id": "somethingDifferent",
"key1": "Value1",
"Key2": "Value2"
}
现在,我想通过使用 key1 和 key2 的值而不是 _id 从集合中检索 DocumentB 的完全匹配,而不返回 Document A,因为我事先不知道它。
如果我只使用 DocumentB 作为查询(没有 _id),Mongo 也会返回 DocumentA,因为它匹配所有的键和值,忽略 DocumentA 有一个额外的键(key3)的事实。
有没有办法在 Mongo 中执行这个“完全匹配”查询? 之后我需要进行检查吗?
假设“完全匹配”是指文档除了查询中的字段之外没有其他字段。
您将需要使用聚合框架来检索对象中的键列表并过滤掉具有意外键的键。 在 mongodb 语法中,它可以是这样的:
db.collection.aggregate([
{
$match: {
"key1": "Value1",
"Key2": "Value2"
}
},
{
$addFields: {
extra_keys: {
$setDifference: [
{
$map: {
input: {
$objectToArray: "$$ROOT"
},
in: "$$this.k"
}
},
[ // <== the list of keys in the query
"_id",
"key1",
"Key2"
]
]
}
}
},
{
$match: {
extra_keys: []
}
}
])
如果您匹配的查询key:value
对与您存储的文档具有相同的顺序,则下面的聚合可能适用于$eq运算符。
db.collection.aggregate([
{
$match: {
$expr: {
$eq: [
{
"key1": "Value1",
"Key2": "Value2"
},
{
$arrayToObject: {
$filter: {
input: {
$objectToArray: "$$ROOT"
},
cond: {
$ne: [
"$$this.k",
"_id"
]
}
}
}
}
]
}
}
}
])
警告:这些对象是相等的
{ {
"key1": "Value1" ---- "key1": "Value1",
"Key2": "Value2", ---- "Key2": "Value2"
} }
这些对象不等于
{ {
"key1": "Value1" --/- "Key2": "Value2",
"Key2": "Value2", -/-- "key1": "Value1"
} }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.