[英]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.