Mongo 简单查询

插入用来测试的数据

db.inventory.insertMany([
{ item: "journal", qty: 25, status: "A", size: { h: 14, w: 21, uom: "cm" }, tags:[ "blank", "red" ] },
{ item: "notebook", qty: 50, status: "A", size: { h: 8.5, w: 11, uom: "in" }, tags: [ "red", "blank" ] },
{ item: "paper", qty: 10, status: "D", size: { h: 8.5, w: 11, uom: "in" }, tags:[ "red", "blank", "plain" ] },
{ item: "planner", qty: 0, status: "D", size: { h: 22.85, w: 30, uom: "cm" }, tags: [ "blank", "red" ] },
{ item: "postcard", qty: 45, status: "A", size: { h: 10, w: 15.25, uom: "cm" }, tags: [ "blue" ]}])

根据id精确查找

db.inventory.find({_id:ObjectId("60d487240b05983cd3c7e55c")})
{ "_id" : ObjectId("60d487240b05983cd3c7e55c"), "item" : "notebook", "qty" : 50, "status" : "A", "size" : { "h" : 8.5, "w" : 11, "uom" : "in" }, "tags" : [ "red", "blank" ] }

查找后格式化输出

> db.inventory.find({_id:ObjectId("60d487240b05983cd3c7e55c")}).pretty()
{
	"_id" : ObjectId("60d487240b05983cd3c7e55c"),
	"item" : "notebook",
	"qty" : 50,
	"status" : "A",
	"size" : {
		"h" : 8.5,
		"w" : 11,
		"uom" : "in"
	},
	"tags" : [
		"red",
		"blank"
	]
}

多个条件查询

> db.inventory.find({"status":"D","qty":0})
{ "_id" : ObjectId("60d487240b05983cd3c7e55e"), "item" : "planner", "qty" : 0, "status" : "D", "size" : { "h" : 22.85, "w" : 30, "uom" : "cm" }, "tags" : [ "blank", "red" ] }

查询结果显示和不显示某个字段Size

> db.inventory.find({"status":"D","qty":0},{size:1})
{ "_id" : ObjectId("60d487240b05983cd3c7e55e"), "size" : { "h" : 22.85, "w" : 30, "uom" : "cm" } }
> db.inventory.find({"status":"D","qty":0},{size:0})
{ "_id" : ObjectId("60d487240b05983cd3c7e55e"), "item" : "planner", "qty" : 0, "status" : "D", "tags" : [ "blank", "red" ] }
> db.inventory.find({"status":"D","qty":0},{_id:0,size:0})
{ "item" : "planner", "qty" : 0, "status" : "D", "tags" : [ "blank", "red" ] }

使用and 条件查询

> db.inventory.find({$and:[{"status":"D"},{"qty":0}]})
{ "_id" : ObjectId("60d487240b05983cd3c7e55e"), "item" : "planner", "qty" : 0, "status" : "D", "size" : { "h" : 22.85, "w" : 30, "uom" : "cm" }, "tags" : [ "blank", "red" ] }

使用or条件查询

> db.inventory.find({$or:[{"status":"D"},{"qty":25}]})
{ "_id" : ObjectId("60d487240b05983cd3c7e55b"), "item" : "journal", "qty" : 25, "status" : "A", "size" : { "h" : 14, "w" : 21, "uom" : "cm" }, "tags" : [ "blank", "red" ] }
{ "_id" : ObjectId("60d487240b05983cd3c7e55d"), "item" : "paper", "qty" : 10, "status" : "D", "size" : { "h" : 8.5, "w" : 11, "uom" : "in" }, "tags" : [ "red", "blank", "plain" ] }
{ "_id" : ObjectId("60d487240b05983cd3c7e55e"), "item" : "planner", "qty" : 0, "status" : "D", "size" : { "h" : 22.85, "w" : 30, "uom" : "cm" }, "tags" : [ "blank", "red" ] }

你可能感兴趣的:(大数据,mongo)