0

How to nested find in mongodb with collection data below :

{
 "_id": {
  "$oid": "585b998297f53460d5f760e6"
 },
 "newspaper": {
  "playerID": "57bffe76b6a70d6e2a3855b7",
  "playerUsername": "dennis",
  "player_newspaper": "{\"ID\":\"57bffe76b6a70d6e2a3855b7\",\"Username\":\"Dennis\",\"itemName\":\"Corn\",\"Comment\":\"Jagung Promo\",\"Date\":\"12/27/2016\"}"
 }
}

My code :

var datex = new Date();
var dates = datex.getMonth() + '/' + datex.getDate() + '/' + datex.getFullYear();
db.playerNewspaper.remove( {"newspaper.player_newspaper.Date": dates } } } ) ;

This is not working.

and

That's how I insert the data:

var currentPlayer = {
        "playerID": playerID,
        "playerUsername": playerUsername,
        "player_newspaper": newspaper

    }; // we construct a new player from the data we are about to input into the player data

    playerDataList.insert(
    {
      "newspaper" : currentPlayer
    } // Uses the $set mongo modifier to set old player data to the current player data
    );

1 Answer 1

2

Your query looks good but problem in your data. According to your query condition you assume that player_newspaper is an object but that data you shown there player_newspaper is a String. So in your query "newspaper.player_newspaper.Date": date not found any document that's why query not working.

Your document structure should be like:

{
    "_id" : ObjectId("585b998297f53460d5f760e6"),
    "newspaper" : {
        "playerID" : "57bffe76b6a70d6e2a3855b7",
        "playerUsername" : "dennis",
        "player_newspaper" : {
            "ID" : "57bffe76b6a70d6e2a3855b7",
            "Username" : "Dennis",
            "itemName" : "Corn",
            "Comment" : "Jagung Promo",
            "Date" : "12/27/2016"
        }
    }
}

Then your query will be working fine.

var datex = new Date();
var dates = datex.getMonth() + '/' + datex.getDate() + '/' + datex.getFullYear();
db.playerNewspaper.remove( {"newspaper.player_newspaper.Date": dates } } } ) ;
Sign up to request clarification or add additional context in comments.

9 Comments

Hi @shaisab, So what the query will look like if the data if like mine ?
Well, I think you should change your data structure. That's not a valid structure or unfortunately you did that while updating or adding. @DennisLiu
So how to insert a data with a structure like yours ?
How get newpaper in "player_newspaper": newspaper ? check that structure
"player_newspaper": newspaper That newspaper is a class that i convert to json string.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.