如何在MongoDB中进行这样的查询
以下是我的文档示例如何在MongoDB中进行这样的查询,mongodb,Mongodb,以下是我的文档示例 { username: 'John', score: 10 }, { username: 'John', score: 9 }, { username: 'John', score: 8 }, { username: 'Alice', score: 9 }, { username: 'Bob', score: 7 } 我想选择所有得分从未达到10分的用户 预期产出: { username: 'Alice', score: 9 }, { us
{ username: 'John', score: 10 },
{ username: 'John', score: 9 },
{ username: 'John', score: 8 },
{ username: 'Alice', score: 9 },
{ username: 'Bob', score: 7 }
我想选择所有得分从未达到10分的用户
预期产出:
{ username: 'Alice', score: 9 },
{ username: 'Bob', score: 7 }
根据您在上述回答中的评论,如果您的文档包含以下文档:
{ "_id" : ObjectId("55713e614e3a37ae89ef7b4b"), "username" : "John", "score" : 10 }
{ "_id" : ObjectId("55713e614e3a37ae89ef7b4c"), "username" : "John", "score" : 9 }
{ "_id" : ObjectId("55713e614e3a37ae89ef7b4d"), "username" : "John", "score" : 8 }
{ "_id" : ObjectId("55713e614e3a37ae89ef7b4e"), "username" : "Alice", "score" : 9 }
{ "_id" : ObjectId("55713e614e3a37ae89ef7b4f"), "username" : "Bob", "score" : 7 }
并且您希望显示那些得分从未被10的用户,这意味着在上述条件下,Alice和Bob
您需要的数据。因此,请检查以下查询:
db.collectionName.find({"username":{"$nin":db.collectionName.distinct("username",{"score":10})}})
这db.collectionName.distinct(“username”,score:10})
distinct返回score:10
的用户的数组,并在find中使用此数组检查distinct
数组中nin
的用户名