使用 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" ] }
广告