我有一个 mongo 集合,我需要在这个集合中查找文档,其中的字段 name 和 address 是相等的。
查了很多,只能找到MongoDb query condition on comparing 2 fields和 MongoDB: Unique and sparse compound indexes with sparse values ,但在这些问题中,他们正在寻找字段 a = 字段 b 的文档,但我需要找到 document1.a == document2.a
最佳答案
您可以使用 Aggregation Framework 查找重复项和 $group
.
示例数据设置:
// Batch insert some test data
db.mycollection.insert([
{a:1, b:2, c:3},
{a:1, b:2, c:4},
{a:0, b:2, c:3},
{a:3, b:2, c:4}
])
聚合查询:
db.mycollection.aggregate(
{ $group: {
// Group by fields to match on (a,b)
_id: { a: "$a", b: "$b" },
// Count number of matching docs for the group
count: { $sum: 1 },
// Save the _id for matching docs
docs: { $push: "$_id" }
}},
// Limit results to duplicates (more than 1 match)
{ $match: {
count: { $gt : 1 }
}}
)
示例输出:
{
"result" : [
{
"_id" : {
"a" : 1,
"b" : 2
},
"count" : 2,
"docs" : [
ObjectId("5162b2e7d650a687b2154232"),
ObjectId("5162b2e7d650a687b2154233")
]
}
],
"ok" : 1
}
https://stackoverflow.com/questions/14770170/
相关文章:
node.js - Mongoose 嵌套对象数组中的唯一值
arrays - Mongoose save() 不更新数据库文档中数组中的值
javascript - mongodb打印没有空格的json,即不漂亮的json
python - 使用 MongoDB ( Python ) 将新属性插入文档
mongodb - 如何检查 mongo db 是否在 Mac 上运行?
spring - Spring Data MongoDB 和 Hibernate OGM for M
java - java - 如何使用java api查询 “like”的mongodb?