var orders = new Array();
var shipping = new Array();
var addresses = ["广西省玉林市", "湖南省岳阳市", "湖北省荆州市", "甘肃省兰州市", "吉林省松原市", "江西省景德镇", "辽宁省沈阳市", "福建省厦门市", "广东省广州市", "北京市朝阳区"];
for (var i = 10000; i < 20000; i++) {
var orderNo = i + Math.random().toString().substr(2, 5);
orders[i] = { orderNo: orderNo, userId: i, price: Math.round(Math.random() * 10000) / 100, qty: Math.floor(Math.random() * 10) + 1, orderTime: new Date(new Date().setSeconds(Math.floor(Math.random() * 10000))) };
var address = addresses[Math.floor(Math.random() * 10)];
shipping[i] = { orderNo: orderNo, address: address, recipienter: "Wilson", province: address.substr(0, 3), city: address.substr(3, 3) }
}
db.order.insert(orders);
db.shipping.insert(shipping);
> db.order.find()
> db.shipping.find()
db.createView(
"<viewName>",
"<source>",
[<pipeline>],
{
"collation" : { <collation> }
}
)
函数 | 解释 |
---|---|
viewName | 必须,视图名称 |
source | 必须,数据源,集合/视图 |
[] | 可选,一组管道 |
collation | 可选,排序规则 |
db.createView(
"orderInfo", //视图名称
"order", //数据源
[
//筛选符合条件的订单,大于当天,这里要注意时区
{ $match: { "orderTime": { $gte: ISODate("2022-01-26T00:00:00.000Z") } }},
//按金额倒序
{ $sort: { "price": -1 } },
//限制10个文档
{ $limit: 10 },
//选择要显示的字段
//0: 排除字段,若字段上使用(_id除外),就不能有其他包含字段
//1: 包含字段
{ $project: { _id: 0, orderNo: 1, price: 1, orderTime: 1 } }
]
)
> db.orderInfo.find()
db.createView(
"orderDetail", //视图名称
"order", //数据源
[
{ $lookup: { from: "shipping", localField: "orderNo", foreignField: "orderNo", as: "shipping" } },
{ $project: { "orderNo": 1, "price": 1, "shipping.address": 1 } }
]
)
db.runCommand(
collMod: "<viewName>",
viewOn: "<source>",
pipeline:[<pipeline>],
{
"collation" : { <collation> }
}
)
函数 | 解释 |
---|---|
viewName | 必须,视图名称 |
source | 必须,数据源,集合/视图 |
[] | 可选,一组管道 |
collation | 可选,排序规则 |
db.runCommand({
collMod: "orderInfo",
viewOn: "order",
pipeline: [
{ $match: { "orderTime": { $gte: ISODate("2020-04-13T16:00:00.000Z") } } },
{ $sort: { "price": -1 } },
{ $limit: 10 },
{ $project: { _id: 0, orderNo: 1, price: 1, qty: 1, orderTime: 1 } }
]
})
> db.orderInfo.find()
db.orderInfo.drop();
> db.orderInfo.find()
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://wwwxz.blog.csdn.net/article/details/124439199
内容来源于网络,如有侵权,请联系作者删除!