Searching for Specific Players and Teams

Introduction

The platform allows you to search for specific Players and Teams in your game with some very easy to use tools.

This tutorial explains ways you can search for players or teams, using:

Searching with NoSQL Explorer

This powerful tool is part of the Data Explorer and allows you to search for anything within your game that is stored in Mongo database collections, right down to the specifics of a certain index. For example, you can search for certain players who have exactly 530 ammunition in their inventory or search for players that share the same name - your search possibilities are endless!

New Games? If you are working with a game that was created after the launch of the Game Data Service in January 2018, you won't be able to create Mongo runtime collections and you must use the Game Data Service to create Data Types to persist custom data in the platform for your game. You can search your Data Types on the Data Explorer page.

More Information: For more information about the SQL Explorer, click here.

Searching the Player System Collection

We'll use the NoSQL explorer to search for a specific player's display name. The display name we'll be looking for will be "Coder".

Here's how we set up the search in the explorer:

Once we submit the search (Using pressing Enter or clicking Find) the players which have Coder as their display name will be retrieved and all their database data are displayed including scriptData, privateData, externalIDs, external authentication, and many more fields that you may or may not want to see. However, when you search for a specific field you can also limit which fields come back from the player collection using the format {"fieldName": 1} to include fields or {"fieldName": 0} to exclude fields. So, for our purpose we're going to limit the search to return displayName and userName fields only:

Searching the Team System Collection

Following the search against the player System collection, by now selecting the System>team collection, you can search for specific teams and view their members, which then allows you to take the member's ID and search for those members:

Using Get Team and List Teams Requests

You can use ListTeamsRequest to list a number of Teams that contain a string or meet a specific type of Team. Once a list comes back, you can use the GetTeamRequest to get the details of one of the teams returned in the list.

Example:

Let's list a max of 10 teams that have the word 'team' in their name using ListTeamsRequest.

{
  "@class": ".ListTeamsRequest",
  "entryCount": 10,
  "offset": 0,
  "teamNameFilter": "team"
}

If such teams exist in our team System Mongo collection, we'll get a list back containing the owner, name, team ID and team type.

{
  "@class": ".ListTeamsResponse",
  "teams": [
    {
      "owner": {
        "achievements": [
          "Fastest_First",
          "Cloud_Achievement"
        ],
        "displayName": "Dummy1",
        "externalIds": {},
        "id": "563b4235e4b0f85acff00a22",
        "online": false,
        "scriptData": {
          "Skill": 1
        },
        "virtualGoods": [
          "Gold_Coin"
        ]
      },
      "teamId": "RedTeam",
      "teamName": "ReadTeam",
      "teamType": "tourniTeam"
    },
    {
      "owner": {
        "displayName": "GSTTwo",
        "externalIds": {},
        "id": "569fa047e4b0504a803a60ad",
        "online": false
      },
      "teamId": "GSTeam",
      "teamName": "GSTeam",
      "teamType": "basic_Team"
    }
  ]
}

We can then take the ID of one of those teams and feed it to the GetTeamRequest. Here's an example request:

{
  "@class": ".GetTeamRequest",
  "ownerId": "",
  "teamId": "RedTeam",
  "teamType": "tourniTeam"
}

If the Team is found, a more comprehensive response comes back with information on the members, their online status, their script data, achievements, virtual goods, and other data.

{
  "@class": ".GetTeamResponse",
  "teams": [
    {
      "members": [
        {
          "achievements": [
            "Fastest_First",
            "Cloud_Achievement"
          ],
          "displayName": "Dummy1",
          "externalIds": {},
          "id": "563b4235e4b0f85acff00a22",
          "online": false,
          "scriptData": {
            "Skill": 1,
            "yawee": "yeeboi"
          },
          "virtualGoods": [
            "Gold_Coin"
          ]
        },
        {
          "achievements": [
            "Fastest_First",
            "Cloud_Achievement"
          ],
          "displayName": "Dummy2",
          "externalIds": {},
          "id": "563b423ce4b0f85acff00a61",
          "online": false,
          "scriptData": {
            "Skill": "1"
          },
          "virtualGoods": [
            "Gold_Coin"
          ]
        }
      ],
      "owner": {
        "achievements": [
          "Fastest_First",
          "Cloud_Achievement"
        ],
        "displayName": "Dummy1",
        "externalIds": {},
        "id": "563b4235e4b0f85acff00a22",
        "online": false,
        "scriptData": {
          "Skill": 1
        },
        "virtualGoods": [
          "Gold_Coin"
        ]
      },
      "teamId": "RedTeam",
      "teamName": "ReadTeam",
      "teamType": "tourniTeam"
    }
  ]
}

Searching with Cloud Code

In addition to the data stored in the player and team Mongo System collections, which you can search using the NoSQL Explorer, you might also want to store player and team details for your game in custom Mongo Runtime collections or custom Data Types using the Game Data Service. You can then search for player and team details stored as custom data while your game executes requests and responses using Cloud Code. You can use this powerful capability to allow your users to find each other using Events you've set up through Cloud Code:

Searching with Cloud Code for Game Data Service

First, we'll need to create a custom game Data Type, which we'll use to keep track of a player's details.

Game Data Service? This section of the tutorial assumes an understanding of the Game Data Service. We strongly recommend that you review the Game Data and the Data Explorer topics before you attempt to follow this tutorial.

To create a custom Data Type that saves your player details:

To retrieve those player details:

Here's our example code:

Registration Response Cloud Code to store player details:

//Saving Player details
if(Spark.getData().error == null){
    //Get player
    var player = Spark.getPlayer();

    //Create entry and get its data object
    var API = Spark.getGameDataService();
    var entry = API.createItem("userDetails", player.getPlayerId());
    var data = entry.getData();

    //Insert details you want to query for in the future
    data.userName = player.getUserName();
    data.displayName = player.getDisplayName();

    //Persist entry
    var status = entry.persistor().persist().error();

    //Check for errors
    if(status){
        Spark.setScriptError("ERROR", "Problem attempting to persist document");
    }
}

To retrieve player details in the future, use the function below anywhere in your Cloud Code:

//SEARCHING PLAYERS
//Create entry and get its data object
var API = Spark.getGameDataService();

//Create a query, in this example we want to find a user with a unique userName
var query = API.S("userName").eq("exampleName");

//Run query on userDetails collection
var resultOBJ = API.queryItems("userDetails", query);

//If our query is successful
if(resultOBJ.error() != null){
    if(resultOBJ.cursor().hasNext()){
        //Get playerID which is set as the entry ID and load player
        Spark.loadPlayer(resultOBJ.cursor().next().getId());    
    }
} else{
    //If our query comes back without results output error
    Spark.setScriptError("ERROR", "Player might not exist, please check userName again")
}


Searching with Cloud Code for Mongo Runtime Collections

We'll need to create a custom collection, which we'll use to keep track of our user's ID and Username.

Important! If you're working on a new game that was created after the Game Data Service was launched in January 2018, you won't be able to create new Mongo Runtime collections using Cloud Code and you'll get an error if you try to do this. See the previous section.

To create a custom collection that saves your player details, do this:

  1. Go to Data Explorer>NoSQL Explorer and in the Collections panel create a Runtime collection.
  2. In your registration response, have some Cloud Code which saves the player's ID and Username upon successful registration into that runtime collection.

Here's our example code:

Registration Response Cloud Code:

if(Spark.getData().error === undefined){
    //Load user details collection, pass in collection name
    var userCollection = Spark.runtimeCollection("userDetails");

    //Get player
    var player = Spark.Spark.getPlayer()
    //Save the the username and ID on the runtime collection
    userCollection.insert({"_id":{"$oid":player.getPlayerId()},"userName":player.getUserName()});
}

To retrieve that information in the future, use the function below anywhere in your Cloud Code:


    //SEARCHING PLAYERS
    //Getting a player based on Query
    var players = Spark.runtimeCollection("userDetails");

    var playerData = players.findOne({"userName" : "coder"}, {_id : 1, userName:1}); //Find the username 'Coder' and return the players that have it.

    //Or you can have the player ID saved
    var playerID = "5602c3dce4b07961f34b68c3" //Manually set the ID

    //Finding the player through their ID
    var playerVar = Spark.loadPlayer(playerData._id.$oid); //or (playerID) //Make a reference for that player through their ID.

    //SEARCHING TEAMS
    //Or you can have the player ID saved
    var teamID = "GameSparks Team" //manually set the ID

    //Finding the player through their ID
    var teamVar = Spark.getTeams().getTeam(teamID) //Make a reference for that team through the ID

Did this page help you? Please enter your feedback below. For questions about using this part of the platform, please contact support here