Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8645563
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 12, 20262026-06-12T12:34:58+00:00 2026-06-12T12:34:58+00:00

I’ve got an issue with an advanced count query with MongoDB. I’m tring to

  • 0

I’ve got an issue with an advanced count query with MongoDB.

I’m tring to count object inside a document field, but only if a previous element matching a query exist and is older in the array.

Let me explain….

I have got a container document, lookin’ like:

{
 "_id" : ...,
 [...]
 "objects" : [ ]
}

Inside the objects fields:
I’ve got object document lookin’ like:

[
  {
    "_id" : ...,
    "name" : "foo",
    "properties" = [ ],
    "time" = 000000042
  }

  {
    "_id" : ...,
    "name" : "bar",
    "properties" = [ ],
    "time" = 000000424
  }

  {
    "_id" : ...,
    "name" : "baz",
    "properties" = [ ],
    "time" = 000004242
  }

For now I count how many container documents contain:
count of container with object 1 (foo),
count of container with object 1 and 2 (foo and bar),
count of container with object 1, 2 and 3 (foo, bar, baz)

But now I want to count foo and bar only if bar is older than foo (using the time field)…
count of container with object 1 (foo),
count of container with object 1 and 2 (foo and bar), AND foo.time < bar.time
count of container with object 1, 2 and 3 (foo, bar, baz) AND foo.time < bar.time < baz.time

The probleme is that the time field needs to change for each container.
With other words: How can I use dynamic query per document

here a sample of code:

foreach ($COUNTER[ARRAY_FIELDS_NAME_TO_COUNT] as $key => $value)
{
// Build the query (Name & properties)
$match[$key] = array('$elemMatch' => array('name' => $value['name']));
foreach ($value['properties'] as $propertyName => $propertyValue)
  $match[$key]['$elemMatch']["properties.$propertyName"] = $propertyValue;

// Time checking
if ($key > 0)
{
  //FIXME with a... dynamics query searching inside current doc??
  //           or   a special var set to the previous object matched...  or MapReduce..
}


// Make the query
$query = array('objects' => array('$all' => $match));

$result[$key]['count'] = $db->person->count($query);
}

I’m new in MongoDB, and I really don’t know what could be the best practice for doing that efficiently!

Regards!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-12T12:34:59+00:00Added an answer on June 12, 2026 at 12:34 pm

    Here is how you can do this with Aggregation Framework in the shell (javascript).

    Note that I’ve split this up into multiple lines for readability, the actual query is the last line. I’ve used foo bar and baz but of course you want to adjust to something more appropriate.

    match = { "$match" : { "objects.name" : "foo" } };
    unwind = { "$unwind" : "$objects" };
    projectDates = {"$project" : {
            "_id" : 1,
            "objects" : 1,
            "fooDate" : {
                "$cond" : [
                    {
                        "$eq" : [
                            "$objects.name",
                            "foo"
                        ]
                    },
                    "$objects.time",
                    0
                ]
            },
            "barDate" : {
                "$cond" : [
                    {
                        "$eq" : [
                            "$objects.name",
                            "bar"
                        ]
                    },
                    "$objects.time",
                    0
                ]
            },
            "bazDate" : {
                "$cond" : [
                    {
                        "$eq" : [
                            "$objects.name",
                            "baz"
                        ]
                    },
                    "$objects.time",
                    0
                ]
            }
        }
    };
    group = {"$group" : {
            "_id" : "$_id",
            "objects" : {
                "$push" : "$objects"
            },
            "maxFooDate" : {
                "$max" : "$fooDate"
            },
            "maxBarDate" : {
                "$max" : "$barDate"
            },
            "maxBazDate" : {
                "$max" : "$bazDate"
            }
        }
    };
    projectCount = {"$project" : {
            "_id" : 1,
            "foos" : {
                "$add" : [
                    1,
                    0
                ]
            },
            "foosAndBars" : {
                "$cond" : [
                    {
                        "$lt" : [
                            "$maxFooDate",
                            "$maxBarDate"
                        ]
                    },
                    1,
                    0
                ]
            },
            "foosBarsAndBazs" : {
                "$cond" : [
                    {
                        "$and" : [
                            {
                                "$lt" : [
                                    "$maxBarDate",
                                    "$maxBazDate"
                                ]
                            },
                            {
                                "$lt" : [
                                    "$maxFooDate",
                                    "$maxBarDate"
                                ]
                            }
                        ]
                    },
                    1,
                    0
                ]
            }
        }
    };
    countFoos = {"$group" : {
            "_id" : "FoosBarsBazs",
            "Foos" : {
                "$sum" : "$foos"
            },
            "FBs" : {
                "$sum" : "$foosAndBars"
            },
            "FBBs" : {
                "$sum" : "$foosBarsAndBazs"
            }
        }
    };
    
    
    db.collection.aggregate([match, unwind, projectDates, projectCount, countFoos]).result
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I want to count how many characters a certain string has in PHP, but
i got an object with contents of html markup in it, for example: string
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I've got a string that has curly quotes in it. I'd like to replace
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I have a French site that I want to parse, but am running into
I want use html5's new tag to play a wav file (currently only supported
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I would like to count the length of a string with PHP. The string
This could be a duplicate question, but I have no idea what search terms

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.