{ "_id" : ObjectId("5c541529fc3e371af7720346"), "name" : "Sanjeev", "hobbies" : [ { "title" : "Trekking", "frequency" : 3 }, { "title" : "Cooking", "frequency" : 4 } ], "phone" : 122311223 }
{ "_id" : ObjectId("5c541529fc3e371af7720347"), "name" : "siddhanth", "hobbies" : [ { "title" : "Trekking", "frequency" : 3 }, { "title" : "Cooking", "frequency" : 4 } ], "phone" : "122311223", "age" : 30 }
{ "_id" : ObjectId("5c54158efc3e371af7720348"), "name" : "Sanjeev", "hobbies" : [ { "title" : "Trekking", "skills" : [ "mountainclimbing" ], "frequency" : 3 }, { "title" : "Cooking", "frequency" : 4 } ], "phone" : 122311223 }
{ "_id" : ObjectId("5c54158efc3e371af7720349"), "name" : "siddhanth", "hobbies" : [ { "title" : "Trekking", "frequency" : 3 }, { "title" : "Cooking", "frequency" : 4 } ], "phone" : "122311223", "age" : 30 }
以上是我收藏的一个例子。
当我执行以下查询时
> db.player.find({hobbies:{$elemMatch:{skills:{$exists:true}}}})
我得到以下结果,其中“爱好”具有“技能”
{ "_id" : ObjectId("5c54158efc3e371af7720348"), "name" : "Sanjeev", "hobbies" : [ { "title" : "Trekking", "skills" : [ "mountainclimbing" ], "frequency" : 3 }, { "title" : "Cooking", "frequency" : 4 } ], "phone" : 122311223 }
但是当我执行
> db.player.find({hobbies:{$elemMatch:{'skills':{$exists:false}}}})
我也获得了具有“技能”的记录。
{ "_id" : ObjectId("5c541529fc3e371af7720346"), "name" : "Sanjeev", "hobbies" : [ { "title" : "Trekking", "frequency" : 3 }, { "title" : "Cooking", "frequency" : 4 } ], "phone" : 122311223 }
{ "_id" : ObjectId("5c541529fc3e371af7720347"), "name" : "siddhanth", "hobbies" : [ { "title" : "Trekking", "frequency" : 3 }, { "title" : "Cooking", "frequency" : 4 } ], "phone" : "122311223", "age" : 30 }
{ "_id" : ObjectId("5c54158efc3e371af7720348"), "name" : "Sanjeev", "hobbies" : [ { "title" : "Trekking", "skills" : [ "mountainclimbing" ], "frequency" : 3 }, { "title" : "Cooking", "frequency" : 4 } ], "phone" : 122311223 }
{ "_id" : ObjectId("5c54158efc3e371af7720349"), "name" : "siddhanth", "hobbies" : [ { "title" : "Trekking", "frequency" : 3 }, { "title" : "Cooking", "frequency" : 4 } ], "phone" : "122311223", "age" : 30 }
我是mongodb的新手。我在这里想念什么?你能解释一下吗?
答案 0 :(得分:1)
db.player.find({ hobbies:{ $elemMatch:{ skills:{ $exists:true }}}})
$elemMatch
遍历数组中的每个元素,并检查条件,如果任何数组元素与返回文档的条件相匹配。
db.player.find({ "hobbies.skills": { $exists: true }})
.dot
表示数组中的每个元素是否满足条件,然后才返回文档。