How do you get a count of listitems of a certain content type without fetching all items

4.1k views Asked by At

So we had a piece of code that set a few elements to display the count of all items in various lists.

Now a requirement has been added that only items of a certain content type can be counted. However, Including a caml query as seen below (The old code has been commented out) has made it far to slow for actual use. (obviously, its fetching thousands of items just to get a count).

Is there a way to count all items of a contenttype in a sharepoint list using javascript that doesn't request all items of every list?

function setCounter() {
    context = new SP.ClientContext.get_current();
    web = this.context.get_web();
    this.lists = web.get_lists();
    context.load(this.lists);
    context.executeQueryAsync(
        Function.createDelegate(this, function () {
            var listsEnumerator = this.lists.getEnumerator();
            while (listsEnumerator.moveNext()) {
                var currentItem = listsEnumerator.get_current();
                for (var i = 0; i < leng; i++) {
                    if (leng == 1) ele = listItemCount;
                    else ele = listItemCount[i];


                    if (decoded == currentItem.get_title()) {
                        ele.parentNode.setAttribute("class", "overview_discussions");

                        // var counter = currentItem.getItems();
                        // ele.innerText = currentItem.get_itemCount();

                        var camlQuery = new SP.CamlQuery();
                        camlQuery.set_viewXml("<Where><BeginsWith><FieldRef Name='ContentTypeName'/><Value Type='Text'>Discussion</Value></BeginsWith></Where>");
                        var counter = currentItem.getItems(camlQuery);

                        context.load(counter);
                        context.executeQueryAsync(function () { ele.innerText = counter.get_count(); }, executeOnFailure);

                        break;
                    }
                }
            }
        }),
        Function.createDelegate(this, executeOnFailure));
}
1

There are 1 answers

0
Gonzix On BEST ANSWER

Nope, but what you can do is minimize the data pulling by setting viewfields. Now is like you are doing a select * when you only need select id

var caml = "<View><ViewFields><FieldRef Name='Id'/></ViewFields></View><Query>your query here</Query>";

After executing the query you just need to cal get_count() as you already do

If you are familiar with jQuery, I suggest you taking a look a this library, is very easy to use and helps you improve your work with object client model. http://spservices.codeplex.com/