使用MongoDB查询列表中的值(不是对象)
要查询列表中的值,请在MongoDB中使用位置运算符($)。让我们创建一个包含文档的集合-
> db.demo628.insertOne({id:1,Name:["Chris","David","John"]}); { "acknowledged" : true, "insertedId" : ObjectId("5e9ae7ea6c954c74be91e6b6") } > db.demo628.insertOne({id:1,Name:["Carol","Sam"]}); { "acknowledged" : true, "insertedId" : ObjectId("5e9ae7f26c954c74be91e6b7") } > db.demo628.insertOne({id:2,Name:["Mike","Sam","John"]}); { "acknowledged" : true, "insertedId" : ObjectId("5e9ae8056c954c74be91e6b8") }
在find()方法的帮助下显示集合中的所有文档-
> db.demo628.find();
这将产生以下输出-
{ "_id" : ObjectId("5e9ae7ea6c954c74be91e6b6"), "id" : 1, "Name" : [ "Chris", "David", "John" ] } { "_id" : ObjectId("5e9ae7f26c954c74be91e6b7"), "id" : 1, "Name" : [ "Carol", "Sam" ] } { "_id" : ObjectId("5e9ae8056c954c74be91e6b8"), "id" : 2, "Name" : [ "Mike", "Sam", "John" ] }
查询列表中的值(不是对象)-
> db.demo628.find({"Name":"John"}, {"id":1, "Name.$":1});
这将产生以下输出-
{ "_id" : ObjectId("5e9ae7ea6c954c74be91e6b6"), "id" : 1, "Name" : [ "John" ] } { "_id" : ObjectId("5e9ae8056c954c74be91e6b8"), "id" : 2, "Name" : [ "John" ] }