Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CouchDB equivalent of Sql NOT IN?

I'm looking for the CouchDB JS view equivalent of the following LinQ query :

    var query =
        from f in context.Feed
        where !(from ds in context.DataSource
                select ds.Feed_ID)
        .Contains(f.ID)
        select f;

Where DataSources have a foreign key to Feeds.

In a word : get all Feeds not associated with a DataSource

Thank you

like image 940
user1992761 Avatar asked Jan 19 '13 11:01

user1992761


People also ask

Is CouchDB a NoSQL database?

Apache CouchDB (CouchDB (link resides outside IBM)) is an open source NoSQL document database that collects and stores data in JSON-based document formats.

Is CouchDB SQL?

CouchDB is a document storage NoSQL database. It provides the facility of storing documents with unique names, and it also provides an API called RESTful HTTP API for reading and updating (add, edit, delete) database documents.

Is CouchDB key value?

CouchDB is one of what many are calling NoSQL solutions. Specifically, CouchDB is a document-oriented database and within each document fields are stored as key-value maps.


1 Answers

You can use the view collation to join feeds and data sources in map:

function(doc) {
  if (!doc.type) return;
  if (doc.type == "feed") emit(doc._id, null);
  if (doc.type == "ds" && doc.feed) emit(doc.feed, null);
}

and reduce to filter those feed ids which have data source documents linking to them. Eg. use of the build-in _count and query with group_level:

http://127.0.0.1:5984/test/_design/join/_view/not_in?group_level=1

for database:

{"id":"1", "type":"feed"}
{"id":"2", "type":"feed"}
{"id":"3", "type":"ds", "feed":1}
{"id":"4", "type":"ds", "feed":1}}

will give you:

{"rows":[
{"key":"1","value":3},
{"key":"2","value":1}
]}

Values >1 are those feed docs which have reference from data sources. To get pure feed list w/o datasources you can omit records with value>1 in client or list function.

Edit: With list function:

function(head, req) {
  var row;
  while (row = getRow()) {
    if (row.value == 1)
      send(row.key + "\n");
  }
}

and query:

http://127.0.0.1:5984/test/_design/join/_list/not_ds/not_in?group_level=1

You will get the final result with feed documents with out reference from data sources. It is plaint text with list of ids, you can also format it for JSON array.

like image 128
Marcin Skórzewski Avatar answered Oct 03 '22 00:10

Marcin Skórzewski