我最近第一次开始使用MongoDB。我需要存储我不一定知道的架构数据。 MongoDB显然看起来非常适合这种情况,是一种无模式数据库。
但是我目前在查询方面正在苦苦思索如何帮助用户构建查询而不必事先知道他们查询哪些字段。
一个例子,假设我有以下集合:
[
{
_id: ObjectId("576b3bc324234cdf7ddsb098"),
timeStamp: ISODate("2015-08-24T09:03:27.887+0000"),
action: "login",
performedBy: {
username: "Annonymous User",
ip: "192.168.0.5"
},
performedOn: {
type: "User",
username: "Stan.Marsh",
ip: "192.168.0.5"
},
outcome: "Success"
},
{
_id: ObjectId("576bbc6c43385c2d84b7b098"),
timeStamp: ISODate("2015-08-24T09:04:27.887+0000"),
action: "update",
performedBy: {
username: "Stan.Marsh",
firstName: "Stan",
lastName: "Marsh",
ip: "192.168.0.5"
},
performedOn: {
Before: {
type: "Product",
Name: "Cheesy Poofs",
weight: "30g"
},
After: {
type: "Product",
Name: "Cheesy Poofs Extreme",
weight: "35g"
}
},
outcome: "Success"
},
{
_id: ObjectId("576b3bc32423dfgdfg45f"),
timeStamp: ISODate("2015-08-24T09:05:27.887+0000"),
action: "logout",
performedBy: {
username: "Stan.Marsh",
firstName: "Stan",
lastName: "Marsh",
ip: "192.168.0.5"
},
outcome: "Success"
}
]
上述数据的实际结构对我来说并不重要,所以请随意提出一些你认为会更好的方法,但我的目标是尽量保持简单。
现在,我需要提供一个可用的查询构建器UI,我需要能够从这些数据中找出哪些字段存在,以及它是什么类型的数据(因此我可以提供相关的UI操作,例如它的日期,例如提供日期范围。
因此,查询上面的集合,例如...(再次具体结构不重要,只是内容)
[
{ name: "timeStamp", type: "Date" },
{ name: "action", type: "String" },
{ name: "performedBy", type: "Object", fields: [
{ name: "username", type: "String" },
{ name: "ip", type: "String" },
{ name: "firstName", type: "String" },
{ name: "lastname", type: "String" }
]
},
{ name: "performedOn", type: "Object", fields: [
{ name: "type", type: "String" },
{ name: "username", type: "String" },
{ name: "ip", type: "String" },
{ name: "before", type: "Object", fields: [
{ name: "type", type: "String" },
{ name: "name", type: "String" },
{ name: "weight", type: "String" }
]
},
{ name: "after", type: "Object", fields: [
{ name: "type", type: "String" },
{ name: "name", type: "String" },
{ name: "weight", type: "String" }
]
}
]
}
]
上面代表了所定义的所有字段的扁平层次结构,可用于构成我所追求的那种界面。请注意,我确实看到了具有相同名称的多个字段存在不同类型的可能性的问题,但是出于示例目的,我希望上述内容有效地传达了我想要实现的目标。
另外需要注意的是,在上面的设计示例中,通过为每个上面的集合对象定义类型然后我可以反映出来,很容易在mongo之外解决这个问题,但是这个的一个重要方面是它是版本不可知,因此允许用户查询他们拥有的数据,无论其模式如何随着时间的推移而演变,这就是为什么这种方法,如果可能的话,更好。
提前谢谢你:)
步骤。