Reputation: 578
I need to query Couchbase database with following conditions. I have documents for Employee entities like
{
"first Name" : "ABC",
"role" : "developer",
"department" : [
{
"name" : "HR",
"country" : "Germany"
},
{
"name" : "Finance",
"country" : "USA"
},
{
"name" : "HR",
"country" : "USA"
}
]
}
how to fetch those documents where department is "HR" in COuchbase ?
Upvotes: 0
Views: 57
Reputation: 3690
Using CouchBase, you could use either Views or Index. I offer you a "map-view" solution.
The map function would look like this :
function(doc) {
if (doc.type === "employee") {
if (doc.department && doc.department.length) {
for (var i = 0; i < doc.department.length; i++) {
emit(doc.department[i].name);
}
}
}
}
Note: This map function us the type "employee". It's highly suggested to group your documents as if they where "tables" by linking them with a key. For example, every employee document could be of type "employee". Also, This map function will emit the same key twice. You can easily change the JavaScript to emit only unique values or you could use a reduce function.
To query the view, you would do something like this:
GET http://localhost:5984/dbname/_design/yourDesignName/_view/byDept?include_docs=true
Output:
{
totalRows: 3,
rows: [{
"id": "ABCEmployee",
"key": "HR",
"value": null,
"doc": {
"first Name": "ABC",
"role": "developer",
"department": [{
"name": "HR",
"country": "Germany"
}, {
"name": "Finance",
"country": "USA"
}, {
"name": "HR",
"country": "USA"
}]
}
},
{
"id": "ABCEmployee",
"key": "Finance",
"value": null,
"doc": {
"first Name": "ABC",
"role": "developer",
"department": [{
"name": "HR",
"country": "Germany"
}, {
"name": "Finance",
"country": "USA"
}, {
"name": "HR",
"country": "USA"
}]
}
},
{
"id": "ABCEmployee",
"key": "HR",
"value": null,
"doc": {
"first Name": "ABC",
"role": "developer",
"department": [{
"name": "HR",
"country": "Germany"
}, {
"name": "Finance",
"country": "USA"
}, {
"name": "HR",
"country": "USA"
}]
}
},
]
}
If you want to query let's say every documents that have the department "HR", do the following :
GET http://localhost:5984/dbname/_design/yourDesignName/_view/byDept?include_docs=true&key="HR"
Upvotes: 2